Skip to content

Commit

Permalink
system fixes && refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
emeebritto committed May 20, 2022
1 parent 0922d4f commit 9db3980
Show file tree
Hide file tree
Showing 16 changed files with 96 additions and 40 deletions.
12 changes: 11 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,15 @@
"@types/uuid": "^8.3.4",
"nodemon": "^2.0.16",
"ts-node": "^10.7.0"
}
},
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": true
}
}
]
]
}
3 changes: 2 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,5 @@ app.get('/', (req:Request, res:Response) => {
app.use('/account', accountRouter)
app.use('/authorization', authorizationRouter)

export default createServer(app);
const httpServer = createServer(app)
export default httpServer;
8 changes: 4 additions & 4 deletions src/common/interfaces/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
export interface UserData {
displayName:string;
username:string;
mail:string;
}

export interface Account {
displayName:string;
username:string;
mail:string;
lastSeen:number;
verified:number;
}

export interface DBAccount {
id:number;
displayName:string;
username:string;
mail:string;
lastSeen:number;
verified:number;
Expand Down Expand Up @@ -42,4 +42,4 @@ export interface LoginInfor {
countryCode:string;
os:string;
userAgent:string;
}
}
7 changes: 5 additions & 2 deletions src/controllers/accountController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@ class AccountController {
return AccountModel.create(account);
}

async getById(id:string | number) {
const account = await AccountModel.findOne({ where: {id: Number(id)} });
async getBy(property:any) {
return AccountModel.findOne({ where: property });
}

async getById(id:string | number) {
const account = await AccountModel.findOne({ where: {id: Number(id)}});
if(account) return account;

throw new InvalidArgumentError('No Found data with this Id!');
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/securityController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ class SecurityController {

async createAccessToken(account:DBAccount, deviceData:any) {
try {
const { id, displayName } = account;
const { id, username } = account;
const payload = {
uuidb: id,
dName: displayName
dName: username
};

if (!KEY) throw new InternalServerError('unavailable service!');
Expand Down
2 changes: 1 addition & 1 deletion src/dataBases/mySql/createTables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import * as models from '../../models';
(async() => {
console.log('CREATING TABLE');
for (let [modelName, modelRef] of Object.entries(models)) {
await modelRef.sync({force : false});
await modelRef.sync({ force: false });
}
})()
8 changes: 5 additions & 3 deletions src/helpers/formValidator.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { UserData } from '../common/interfaces';
import { UserData } from '../common/interfaces';
import accountController from '../controllers/accountController';

const formValidator = (userData:UserData): boolean => {
const formValidator = async(userData:UserData): Promise<boolean> => {
const errors = [
Object.keys(userData).length === 0,
userData.displayName.length > 14 || userData.displayName.length < 4,
await accountController.getBy({ mail: userData.mail }),
userData.username.length > 14 || userData.username.length < 4,
userData.mail.length > 40 || userData.mail.length < 8
]

Expand Down
6 changes: 3 additions & 3 deletions src/mailer/verificationMail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,10 @@ function mailHtml(data:LoginInfor, code:string) {
<p>HOSTNAME: ${data.hostname}</p>
<p>OS: ${data.os}</p>
<div class="actions_section">
<a href="#">
<a href="http://localhost:7050/authorization/${code}?mail=${data.mail}&authorized=allow">
<button class="actions_btn">Yes, authorize</button>
</a>
<a href="#">
<a href="http://localhost:7050/authorization/${code}?mail=${data.mail}&authorized=deny">
<button class="actions_btn">No, deny</button>
</a>
</div>
Expand All @@ -100,7 +100,7 @@ function mailHtml(data:LoginInfor, code:string) {
class VerificationMail extends Mail {
constructor(data:LoginInfor, code:string) {
super({
from: '"Nordly Center" <noreply@nordly.com>',
from: '"Nordly Center" <nordly.team@nordly.com>',
to: data.mail,
subject: 'Verification Mail',
text: mailText(data),
Expand Down
14 changes: 8 additions & 6 deletions src/models/accountModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {

class AccountModel extends Model<InferAttributes<AccountModel>, InferCreationAttributes<AccountModel>> {
declare id: CreationOptional<number>;
declare displayName:string;
declare username:string;
declare mail:string;
declare lastSeen:number;
declare verified:number;
Expand All @@ -24,20 +24,22 @@ AccountModel.init(
autoIncrement: true,
primaryKey: true
},
displayName: {
username: {
type: new DataTypes.STRING(20),
allowNull: false
allowNull: false,
unique: true
},
mail: {
type: new DataTypes.STRING(40),
allowNull: false
allowNull: false,
unique: true
},
lastSeen: {
type: DataTypes.STRING(128),
type: new DataTypes.STRING(128),
allowNull: false
},
verified: {
type: DataTypes.STRING(1),
type: new DataTypes.STRING(1),
allowNull: false
},
createdAt: DataTypes.DATE,
Expand Down
2 changes: 1 addition & 1 deletion src/routers/account/accountData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const redisDB = redis.connection();
interface AccountData {
currentDevice?:any;
account?: {
displayName:string;
username:string;
mail:string;
lastSeen:number;
}
Expand Down
17 changes: 8 additions & 9 deletions src/routers/account/createAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,11 @@ import mailController from '../../controllers/mailController';

const createAccount = async (req:Request, res:Response) => {
await accountController.dropOffAccounts();

const { newUser, deviceData=null } = req.body;

if (!newUser) return res.status(401).json({ msg: "invalid form!" });
const hasError = await formValidator(newUser);
const invalidDevice = !deviceData || !deviceData.localInfor.YourFuckingIPAddress || !deviceData.platform;

const invalidDevice = !deviceData || !deviceData.locationData.YourFuckingIPAddress || !deviceData.platform;
if (hasError) return res.status(401).json({ msg: 'account was denied' });
if (invalidDevice) return res.status(401).json({ msg: 'Unknown Device Data'})

Expand All @@ -32,13 +31,13 @@ const createAccount = async (req:Request, res:Response) => {
const loginData = {
status: "requesting Sign-Up authorization",
mail: dbUserData.mail,
ip: deviceData.localInfor.YourFuckingIPAddress,
ip: deviceData.locationData.YourFuckingIPAddress,
date: moment().format('LL'),
time: moment().format('LTS'),
location: deviceData.localInfor.YourFuckingLocation,
ISP: deviceData.localInfor.YourFuckingISP,
hostname: deviceData.localInfor.YourFuckingHostname,
countryCode: deviceData.localInfor.YourFuckingCountryCode,
location: deviceData.locationData.YourFuckingLocation,
ISP: deviceData.locationData.YourFuckingISP,
hostname: deviceData.locationData.YourFuckingHostname,
countryCode: deviceData.locationData.YourFuckingCountryCode,
os: deviceData.platform,
userAgent: deviceData.userAgent
}
Expand All @@ -64,5 +63,5 @@ export default createAccount;
// doNotTrack:string;
// cookieEnabled:string;
// };
// localInfor:any;
// locationData:any;
// }
22 changes: 22 additions & 0 deletions src/routers/account/evenExists.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Request, Response } from 'express';
import accountController from '../../controllers/accountController';

interface EvenExistsResponse {
hasEvenUsername:boolean | null;
hasEvenMail:boolean | null;
}

const evenExists = async(req:Request, res:Response) => {
const { username=null, mail=null } = req.query || {};

try {
const hasEvenUsername = username ? Boolean(await accountController.getBy({ username })) : null;
const hasEvenMail = mail ? Boolean(await accountController.getBy({ mail })) : null;
res.status(200).json({ hasEvenUsername, hasEvenMail });
} catch(err) {
console.error(err);
res.status(500).json({ msg: 'inexpected error' });
}
};

export default evenExists;
5 changes: 5 additions & 0 deletions src/routers/account/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import accessAccount from './accessAccount';
import createFastToken from './createFastToken';
import accessFastToken from './accessFastToken';
import accountData from './accountData';
import evenExists from './evenExists';
import authenticatonMiddlewares from './authenticationMiddlewares';

const router = express.Router();
Expand All @@ -19,6 +20,10 @@ router
.route('/')
.get(accountData)

router
.route('/exists')
.get(evenExists)

router
.route('/createFastToken')
.get(createFastToken)
Expand Down
5 changes: 4 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import dotenv from 'dotenv';
import httpServer from './app';
import socket from './socket';
import './startup';
dotenv.config();

socket.start(httpServer);

const DEV_ENV_PORT = process.env.DEV_ENV_PORT;
const PORT = process.env.PORT || DEV_ENV_PORT;

httpServer.listen(PORT, () => {
console.log('Started: ' + new Date());
if(DEV_ENV_PORT) console.log(`url: http://localhost:${PORT}/`);
if (DEV_ENV_PORT) console.log(`url: http://localhost:${PORT}/`);
});
17 changes: 13 additions & 4 deletions src/socket.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
import { Server } from "socket.io";
import httpServer from './app';
import mailController from "./controllers/mailController";
import securityController from './controllers/securityController';
const io = new Server(httpServer);

interface Identification {
mail:string;
socketCode:string;
}

class Socket {
sockets:any[];
ioInstance:any;

constructor() {
this.sockets = [];
io.on('connection', socket => {
this.ioInstance = null;
}

start(httpServer:any) {
this.ioInstance = new Server(httpServer);
this.ioInstance.on('connection', (socket:any) => {
console.log(`socket (${socket.id}) connected.`);
socket.on("checkMail", async({ mail, socketCode }, callback) => {
socket.on("checkMail", async({ mail, socketCode }:Identification, callback:(s:any) => void) => {
const invalidMail = !mail || mail.length < 15 || !socketCode;
if (invalidMail) return callback({ error: true, status: 401, msg: "invalid mail!" });
const isValid = await securityController.isValidTempCode(mail, socketCode, "socket_code");
Expand Down
4 changes: 2 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "es5",
"target": "ES2021",
"baseUrl": "src",
"paths": {
"common": ["common"],
Expand All @@ -22,4 +22,4 @@
"esModuleInterop": true,
"resolveJsonModule": true
}
}
}

0 comments on commit 9db3980

Please sign in to comment.