parent
ee937b8c3e
commit
ca8d8a2bd0
@ -1,67 +1,55 @@
|
||||
import express, { Application } from 'express';
|
||||
import cors from 'cors';
|
||||
import { MONGO_PASSWORD } from './config';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import bodyParser from 'body-parser';
|
||||
import Controller from './controller/interfaces/IController';
|
||||
import Controller from './controllers/interfaces/IController';
|
||||
import mongoose from 'mongoose';
|
||||
|
||||
class App {
|
||||
public express: Application;
|
||||
public port: number;
|
||||
public dataBase: null;
|
||||
|
||||
public server: any;
|
||||
|
||||
constructor(controllers: Controller[], port: number) {
|
||||
this.express = express();
|
||||
this.port = port;
|
||||
this.dataBase = null;
|
||||
|
||||
this.initialiseDatabase();
|
||||
this.initialiseMiddleware();
|
||||
this.initialiseControllers(controllers);
|
||||
|
||||
this.initDatabase();
|
||||
this.initMiddleware();
|
||||
this.initControllers(controllers);
|
||||
}
|
||||
|
||||
private initialiseMiddleware(): void {
|
||||
private initMiddleware(): void {
|
||||
this.express.use(cors());
|
||||
this.express.use(cookieParser());
|
||||
|
||||
|
||||
this.express.use(express.json());
|
||||
this.express.use(express.urlencoded({ extended: false }));
|
||||
|
||||
this.express.use(bodyParser.json());
|
||||
this.express.use(bodyParser.urlencoded({
|
||||
extended: true
|
||||
}));
|
||||
|
||||
}
|
||||
|
||||
private initialiseControllers(controllers: Controller[]): void {
|
||||
private initControllers(controllers: Controller[]): void {
|
||||
controllers.forEach((controller: Controller) => {
|
||||
this.express.use('/api', controller.router);
|
||||
this.express.get('/toto', (req, res) => {
|
||||
res.send('Hello World!');
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
public listen(): void {
|
||||
const server = this.express.listen(this.port, () => {
|
||||
this.express.listen(this.port, () => {
|
||||
console.log(`[server] : App listening on the port ${this.port}`);
|
||||
});
|
||||
}
|
||||
|
||||
private initialiseDatabase(): void {
|
||||
const MONGO_URL = "mongodb+srv://fladDevDb:ZslYlNRWIOUU7i6o@fladcluster.b29tytu.mongodb.net/?retryWrites=true&w=majority"
|
||||
private initDatabase(): void {
|
||||
const MONGO_URL = `mongodb+srv://FladDev:${MONGO_PASSWORD}@flad.mliekr2.mongodb.net/?retryWrites=true&w=majority`;
|
||||
mongoose.connect(MONGO_URL)
|
||||
.then(() => console.log("Connect to MongoDB database successfully"))
|
||||
.catch(error => console.log("Error connecting : " + error));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default App;
|
@ -1,24 +1,22 @@
|
||||
import Controller from './interfaces/IController';
|
||||
import IController from './interfaces/IController';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import HttpException from '../exception/HttpException';
|
||||
import axios from 'axios';
|
||||
import qs from 'qs';
|
||||
|
||||
class SpotifyController implements Controller {
|
||||
class SpotifyController implements IController {
|
||||
public path = '/spotify';
|
||||
public router = Router();
|
||||
|
||||
constructor() {
|
||||
console.log("useeeee");
|
||||
|
||||
this.initialiseRoutes();
|
||||
}
|
||||
|
||||
initialiseRoutes() {
|
||||
this.router.get(`${this.path}/exchange`,this.login);
|
||||
this.router.get(`${this.path}/callback`,this.getAccessToken);
|
||||
this.router.get(`${this.path}/refresh`,this.getRefreshToken);
|
||||
this.router.get(`${this.path}/spot`, this.getSpot);
|
||||
|
||||
}
|
||||
|
||||
|
@ -1,254 +0,0 @@
|
||||
import { Router, Request, Response, NextFunction, RequestHandler } from 'express';
|
||||
import Controller from './interfaces/IController';
|
||||
import HttpException from '../exception/HttpException';
|
||||
// import LocationService from '../../service/LocationService';
|
||||
import IUser from '../models/User';
|
||||
import UserService from '../services/UserService';
|
||||
import validator from '../database/User/UserValidation'
|
||||
import validationMiddleware from '../middlewares/validation/ValidatorMiddleware';
|
||||
import authenticator from '../middlewares/authMiddleware'
|
||||
import LocationService from '../services/LocationService';
|
||||
class UserController implements Controller {
|
||||
public path = '/users';
|
||||
public router = Router();
|
||||
private userService = new UserService();
|
||||
private locationService = new LocationService();
|
||||
|
||||
constructor() {
|
||||
this.initialiseRoutes();
|
||||
}
|
||||
|
||||
private initialiseRoutes(): void {
|
||||
this.router.post(
|
||||
`${this.path}/register`,
|
||||
validationMiddleware(validator.register),
|
||||
this.register
|
||||
);
|
||||
this.router.post(
|
||||
`${this.path}/login`,
|
||||
validationMiddleware(validator.login),
|
||||
this.login
|
||||
);
|
||||
this.router.get(`${this.path}`, authenticator, this.getUser);
|
||||
this.router.get(`${this.path}/nextTo`, authenticator, this.getUserNext);
|
||||
|
||||
|
||||
// //create
|
||||
// this.router.post(`${this.path}`,this.createUser);
|
||||
|
||||
// // // get One
|
||||
// this.router.get (`${this.path}/:userId`, this.getUserById);
|
||||
// // // get All
|
||||
// this.router.get (`${this.path}`, this.getAllUsers);
|
||||
// //update One
|
||||
// this.router.put (`${this.path}/:userId`, this.updateUser);
|
||||
// //Delete One
|
||||
// this.router.delete (`${this.path}/:userId`, this.deleteUser);
|
||||
|
||||
}
|
||||
|
||||
// private createUser = async (
|
||||
// req: Request,
|
||||
// res: Response,
|
||||
// next: NextFunction
|
||||
// ): Promise<Response | void> => {
|
||||
// try {
|
||||
|
||||
// console.log(req.body);
|
||||
// const reqBody:CreateTaskReqBody = Object.assign({}, req.body);
|
||||
// checkIfIsValidCreateTaskReqBody(reqBody);
|
||||
// await this.userService.createUserById(reqBody.fin
|
||||
// );
|
||||
|
||||
// res.status(200).send({ status: "Success", msg: "Success add" });
|
||||
|
||||
|
||||
// } catch (error) {
|
||||
// next(new HttpException(400, 'Cannot create post'));
|
||||
// }
|
||||
// };
|
||||
// private readonly getUserById: RequestHandler = async (
|
||||
// req: Request,
|
||||
// res: Response,
|
||||
// next: NextFunction
|
||||
// ): Promise<Response | void> => {
|
||||
// try {
|
||||
// const id = req.params.taskId;
|
||||
// const userId = req.params.userId;
|
||||
|
||||
// const data = await this.userService.getUserById(id, userId);
|
||||
// res.status(201).send(data);
|
||||
|
||||
// }
|
||||
// catch(error){
|
||||
// next(new HttpException(400, 'Cannot create post'));
|
||||
// }
|
||||
|
||||
// }
|
||||
// private readonly getAllUsers: RequestHandler = async (
|
||||
// req: Request,
|
||||
// res: Response,
|
||||
// next: NextFunction
|
||||
// ): Promise<Response | void> => {
|
||||
// try {
|
||||
// const userId = req.params.userId;
|
||||
// const tasks = await this.userService.getUsers(userId);
|
||||
// const responseList = tasks.map(task => new TaskResumedRes(task));
|
||||
// res.status(201).send(responseList);
|
||||
|
||||
// }
|
||||
// catch(error){
|
||||
// next(new HttpException(400, 'Cannot get user task'));
|
||||
// }
|
||||
|
||||
// }
|
||||
|
||||
// private deleteUser = async (
|
||||
// req: Request,
|
||||
// res: Response,
|
||||
// next: NextFunction
|
||||
// ): Promise<Response | void> => {
|
||||
// try {
|
||||
// const id = req.params.taskId;
|
||||
// const userId = req.params.userId;
|
||||
// await this.userService.DeleteUser(id, userId);
|
||||
// return res.status(200).send({ status: "Success", msg: "Data Removed" });
|
||||
// } catch (error) {
|
||||
// next(new HttpException(400, 'Cannot create post'));
|
||||
// }
|
||||
// };
|
||||
|
||||
// private updateUser = async (
|
||||
// req: Request,
|
||||
// res: Response,
|
||||
// next: NextFunction
|
||||
// ): Promise<Response | void> => {
|
||||
// try {
|
||||
|
||||
// const taskId = req.params.taskId;
|
||||
// const userId = req.params.userId;
|
||||
// const reqBody:CreateTaskReqBody = Object.assign({}, req.body);
|
||||
|
||||
// const updatedTask = await this.userService.UpdateTask(
|
||||
// // req.auth!.uid,
|
||||
// taskId,
|
||||
// userId,
|
||||
// // firebase.auth().currentUser.getIdToken()
|
||||
// reqBody.nom,
|
||||
// reqBody.description,
|
||||
// reqBody.logo,
|
||||
// reqBody.duration,
|
||||
// reqBody.done,
|
||||
// // reqBody.tags,
|
||||
// reqBody.repepat,
|
||||
// reqBody.deb,
|
||||
// reqBody.fin
|
||||
// );
|
||||
// // res.send('Success add');
|
||||
// // res.status(201).json({ task });
|
||||
// res.status(204).send(`Update a new contact: ${updatedTask}`);
|
||||
// } catch (error) {
|
||||
// console.log(error);
|
||||
// next(new HttpException(403, 'Cannot create post'));
|
||||
// }
|
||||
// };
|
||||
|
||||
|
||||
private register = async (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<Response | void> => {
|
||||
try {
|
||||
// the FladId should be created by the Userservice
|
||||
const { name, email, password , idFlad, idSpotify } = req.body;
|
||||
console.log(name, email, password, idFlad, idSpotify);
|
||||
|
||||
const token = await this.userService.register(
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
idFlad,
|
||||
idSpotify
|
||||
);
|
||||
|
||||
res.status(201).json({ token });
|
||||
} catch (error : any) {
|
||||
next(new HttpException(400, error.message));
|
||||
}
|
||||
};
|
||||
|
||||
private login = async (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<Response | void> => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
|
||||
const token = await this.userService.login(email, password);
|
||||
|
||||
res.status(200).json({ token });
|
||||
} catch (error : any) {
|
||||
next(new HttpException(400, error.message));
|
||||
}
|
||||
};
|
||||
|
||||
private getUser = (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Response | void => {
|
||||
if (!req.user) {
|
||||
return next(new HttpException(404, 'No logged in user'));
|
||||
}
|
||||
|
||||
res.status(200).send({ data: req.user });
|
||||
};
|
||||
|
||||
private getUserNext = async (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<Response | void> => {
|
||||
try {
|
||||
const longitude = Number(req.query.longitude);
|
||||
const latitude = Number(req.query.latitude);
|
||||
//verify::val_int(){
|
||||
console.log('woooooooooooooo' + req);
|
||||
if (isNaN(longitude) || isNaN(latitude)) {
|
||||
console.log('============' + longitude)
|
||||
console.log('============' + latitude)
|
||||
console.log('Impossible de convertir la chaîne en nombre');
|
||||
}
|
||||
//}
|
||||
const userId = req.user.idFlad;
|
||||
const musicId = String(req.query.currentMusic);
|
||||
console.log('============' + longitude)
|
||||
console.log('============' + latitude)
|
||||
console.log('daaaaaaaaaaaaaaaaaaaaaa' + musicId);
|
||||
const data = await this.locationService.getNearUser(userId,musicId,latitude,longitude);
|
||||
console.log(data);
|
||||
res.status(201).send(data);
|
||||
|
||||
}
|
||||
catch(error : any){
|
||||
next(new HttpException(400, 'Cannot create get netUser'));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
export default UserController;
|
||||
|
||||
|
||||
|
||||
declare global {
|
||||
namespace Express {
|
||||
export interface Request {
|
||||
user: IUser;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,111 @@
|
||||
import { Router, Request, Response, NextFunction, RequestHandler } from 'express';
|
||||
import IController from './interfaces/IController';
|
||||
import HttpException from '../exception/HttpException';
|
||||
import User from '../models/User';
|
||||
import UserService from '../services/UserService';
|
||||
import validator from '../middlewares/UserValidation'
|
||||
import validationMiddleware from '../middlewares/validationMiddleware';
|
||||
import authenticator from '../middlewares/authMiddleware'
|
||||
import LocationService from '../services/LocationService';
|
||||
|
||||
class UserController implements IController {
|
||||
public path = '/users';
|
||||
public router = Router();
|
||||
private userService = new UserService();
|
||||
private locationService = new LocationService();
|
||||
|
||||
constructor() {
|
||||
this.initRoutes();
|
||||
}
|
||||
|
||||
private initRoutes(): void {
|
||||
this.router.post(
|
||||
`${this.path}/register`,
|
||||
validationMiddleware(validator.register),
|
||||
this.register
|
||||
);
|
||||
this.router.post(
|
||||
`${this.path}/login`,
|
||||
validationMiddleware(validator.login),
|
||||
this.login
|
||||
);
|
||||
this.router.get(`${this.path}`, authenticator, this.getUser);
|
||||
this.router.get(`${this.path}/nextTo`, authenticator, this.getUserNext);
|
||||
}
|
||||
|
||||
private register = async (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<Response | void> => {
|
||||
try {
|
||||
const { name, email, password, idSpotify } = req.body;
|
||||
const token = await this.userService.register(
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
idSpotify
|
||||
);
|
||||
res.status(201).json({ token });
|
||||
} catch (error: any) {
|
||||
next(new HttpException(400, error.message));
|
||||
}
|
||||
};
|
||||
|
||||
private login = async (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<Response | void> => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
const token = await this.userService.login(email, password);
|
||||
res.status(200).json({ token });
|
||||
} catch (error: any) {
|
||||
next(new HttpException(400, error.message));
|
||||
}
|
||||
};
|
||||
|
||||
private getUser = (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Response | void => {
|
||||
if (!req.user) {
|
||||
return next(new HttpException(404, 'No logged in user'));
|
||||
}
|
||||
res.status(200).send({ data: req.user });
|
||||
};
|
||||
|
||||
private getUserNext = async (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<Response | void> => {
|
||||
try {
|
||||
const longitude = Number(req.query.longitude);
|
||||
const latitude = Number(req.query.latitude);
|
||||
if (isNaN(longitude) || isNaN(latitude)) {
|
||||
console.log('Unable to convert string to number');
|
||||
throw new Error('Unable to convert string to number');
|
||||
}
|
||||
const userId = req.user.id;
|
||||
const musicId = String(req.query.currentMusic);
|
||||
const data = await this.locationService.getNearUser(userId, musicId, latitude, longitude);
|
||||
res.status(201).send(data);
|
||||
}
|
||||
catch (error: any) {
|
||||
next(new HttpException(400, 'Cannot create get netUser: ' + error.message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default UserController;
|
||||
|
||||
declare global {
|
||||
namespace Express {
|
||||
export interface Request {
|
||||
user: User;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
import { Schema } from 'mongoose';
|
||||
|
||||
interface IToken extends Object {
|
||||
id: Schema.Types.ObjectId;
|
||||
expiresIn: number;
|
||||
}
|
||||
|
||||
export default IToken;
|
@ -1,8 +0,0 @@
|
||||
import { Schema, model } from 'mongoose';
|
||||
|
||||
const notificationSchema = new Schema({
|
||||
type: {type: String, required: true},
|
||||
content: {type: String, required: true}
|
||||
});
|
||||
|
||||
export default {Notification: model("nofitication", notificationSchema)}
|
@ -1,59 +1,21 @@
|
||||
export interface Position {
|
||||
/**
|
||||
* Creation timestamp for coords
|
||||
*/
|
||||
timestamp: number;
|
||||
/**
|
||||
* The GPS coordinates along with the accuracy of the data
|
||||
*/
|
||||
coords: {
|
||||
/**
|
||||
* Latitude in decimal degrees
|
||||
*/
|
||||
latitude: number;
|
||||
/**
|
||||
* longitude in decimal degrees
|
||||
*/
|
||||
longitude: number;
|
||||
};
|
||||
}
|
||||
export class PlacePosition implements Position {
|
||||
timestamp: number;
|
||||
coords: {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
};
|
||||
constructor(timestamp: number,latitude : number ,longitude: number){
|
||||
this.timestamp = timestamp;
|
||||
this.coords = {latitude, longitude};
|
||||
}
|
||||
}
|
||||
import { Document } from 'mongoose';
|
||||
|
||||
export class UserLocation {
|
||||
uuid: string;
|
||||
userId: string;
|
||||
musicId : string;
|
||||
latitude : number;
|
||||
longitude: number;
|
||||
musicId : string;
|
||||
constructor(uuid: string, musicId : string,latitude: number, longitude: number){
|
||||
this.uuid = uuid;
|
||||
constructor(userId: string, musicId : string,latitude: number, longitude: number){
|
||||
this.userId = userId;
|
||||
this.musicId = musicId;
|
||||
this.latitude = latitude;
|
||||
this.longitude = longitude;
|
||||
}
|
||||
}
|
||||
|
||||
export class Place{
|
||||
position: Position;
|
||||
address: Address;
|
||||
constructor(address: Address,position: Position){
|
||||
this.position = position;
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export type Address = {
|
||||
street : string;
|
||||
city : string;
|
||||
state : string;
|
||||
zip : string;
|
||||
export class Location extends Document {
|
||||
userId: string;
|
||||
musicId: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
}
|
@ -1,27 +1,6 @@
|
||||
import jwt from 'jsonwebtoken';
|
||||
import IUser from './User';
|
||||
import IToken from '../database/IToken';
|
||||
import { Schema } from 'mongoose';
|
||||
|
||||
export const createToken = (user: IUser): string => {
|
||||
return jwt.sign({ id: user._id }, "foo" as jwt.Secret, {
|
||||
expiresIn: '100d',
|
||||
});
|
||||
};
|
||||
|
||||
export const verifyToken = async (
|
||||
token: string
|
||||
): Promise<jwt.VerifyErrors | IToken> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
jwt.verify(
|
||||
token,
|
||||
"foo" as jwt.Secret,
|
||||
(err, payload) => {
|
||||
if (err) return reject(err);
|
||||
|
||||
resolve(payload as IToken);
|
||||
}
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export default { createToken, verifyToken };
|
||||
export default interface Token extends Object {
|
||||
id: Schema.Types.ObjectId;
|
||||
expiresIn: number;
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
import jwt from 'jsonwebtoken';
|
||||
import User from '../models/User';
|
||||
import Token from '../models/Token';
|
||||
|
||||
export const createToken = (user: User): string => {
|
||||
return jwt.sign({ id: user._id }, "dave" as jwt.Secret, {
|
||||
expiresIn: '1d',
|
||||
});
|
||||
};
|
||||
|
||||
export const verifyToken = async (
|
||||
token: string
|
||||
): Promise<jwt.VerifyErrors | Token> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
jwt.verify(
|
||||
token,
|
||||
"dave" as jwt.Secret,
|
||||
(err, payload) => {
|
||||
if (err) return reject(err);
|
||||
resolve(payload as Token);
|
||||
}
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export default { createToken, verifyToken };
|
Loading…
Reference in new issue