Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion 19-semana/futurebook/src/data/feedDataBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export class FeedDB extends BaseDB implements FeedGateway{
return undefined;
};

return result[0].map((post: any) => {
return await result[0].map((post: any) => {
return new Feed(
post.id,
post.photo,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ export interface UserGateway {
signUp(user: User): Promise<void>;
login(email: string): Promise<User | undefined>;
getAllUsers(): Promise<User[] | undefined>;
getUserById(id: string, email: string): Promise<User | undefined>;
getUserById(id: string): Promise<User | undefined>;
updatePassword(id: string, password: string): Promise<void>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export interface VideoGateway{
createVideo(video: Video): Promise<void>;
getVideos(orderBy: string, orderType: string, limit: number, offset: number): Promise<Feed[] | undefined>;
getVideoById(id: string): Promise<Feed | undefined>;
deleteVideo(id: string): Promise<void>;
updateVideo(id: string, description: string, title: string): Promise<void>;
getVideoByUser(id: string): Promise<Feed[] | undefined>;
deleteVideo(id: string, user_id: string): Promise<void>;
updateVideo(id: string, user_id: string, title: string, description: string): Promise<void>;
getAllUserVideos(id: string): Promise<Feed[] | undefined>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export class SignUpUC {
if(user){
throw new Error("This email has already been registered!")
}

const id = v4()

let type = UserType.USER
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { UserGateway } from "../../gateways/userGateway";
import { AuthenticationGateway } from "../../gateways/authenticationGateway";
import { CryptographyGateway } from "../../gateways/cryptographyGateway";
import { InvalidParameterError } from "../../error/InvalidParams";

export class UpdatePasswordUC {
constructor(
private userGateway: UserGateway,
private authenticationGateway: AuthenticationGateway,
private cryptographyGateway: CryptographyGateway
){}

public async execute(input: UpdatePasswordUCInput): Promise<UpdatePasswordUCOutput>{
const userInfo = await this.authenticationGateway.getUsersInfoFromToken(input.token)

if(!userInfo){
throw new Error("User not found!")
}

const user = await this.userGateway.getUserById(userInfo.id)

if(!user){
throw new Error("User not found!")
}

const oldPassword = await this.cryptographyGateway.compare(input.oldPassword, user.getPassword());

if(!oldPassword){
throw new InvalidParameterError("Invalid password!");
};

const newPassword = await this.cryptographyGateway.encrypt(input.newPassword)

await this.userGateway.updatePassword(userInfo.id, newPassword)

return {
message: "Password updated successfully!"
}
}
}

export interface UpdatePasswordUCInput{
token: string;
oldPassword: string;
newPassword: string;
}

export interface UpdatePasswordUCOutput{
message: string;
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class CreateVideoUC {
const userInfo = this.authenticationGateway.getUsersInfoFromToken(input.token)

if(!userInfo){
throw new Error("User info are wrong")
throw new Error("User info is wrong")
}

const video = new Video(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ export class DeleteVideoUC{
throw new Error("Video not found")
}

await this.videoGateway.deleteVideo(input.id)
if(userInfo.id !== video.getUser_id()){
throw new Error("You cannot delete this Video")
}

await this.videoGateway.deleteVideo(input.id, userInfo.id)

return {
message: `Video ${input.id} Deleted Successfully!`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import { VideoGateway } from "../../gateways/videoGateway";
import { AuthenticationGateway } from "../../gateways/authenticationGateway";
import { Feed } from "../../entites/feed";

export class GetVideoByUserUC {
export class GetAllUserVideosUC {
constructor(
private videoGateway: VideoGateway,
private authenticationGateway: AuthenticationGateway
){}

public async execute(input: GetVideoByUserUCInput): Promise<GetVideoByUserUCOuput>{
public async execute(input: GetAllUserVideosUCInput): Promise<GetAllUserVideosUCOuput>{
const userInfo = await this.authenticationGateway.getUsersInfoFromToken(input.token)

let videos: Feed[] | undefined;
Expand All @@ -18,10 +18,10 @@ export class GetVideoByUserUC {
}

if(input.id){
videos = await this.videoGateway.getVideoByUser(input.id)
videos = await this.videoGateway.getAllUserVideos(input.id)

} else if (!input.id){
videos = await this.videoGateway.getVideoByUser(userInfo.id)
videos = await this.videoGateway.getAllUserVideos(userInfo.id)
}

if(!videos) {
Expand All @@ -45,16 +45,16 @@ export class GetVideoByUserUC {
}
}

export interface GetVideoByUserUCInput {
export interface GetAllUserVideosUCInput {
token: string;
id: string;
}

export interface GetVideoByUserUCOuput {
videos: GetVideoByUserUCOutputVideo[]
export interface GetAllUserVideosUCOuput {
videos: GetAllUserVideosUCOutputVideo[]
}

export interface GetVideoByUserUCOutputVideo {
export interface GetAllUserVideosUCOutputVideo {
id: string;
title: string;
link: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,18 @@ export class UpdateVideoUC {
if(!userInfo){
throw new Error("You must be connected!")
}

const video = await this.videoGateway.getVideoById(input.id);

if(!video){
throw new Error("Video not found");
}

await this.videoGateway.updateVideo(input.id, input.title, input.description)
if(userInfo.id !== video.getUser_id()){
throw new Error("You cannot update this video!")
}

await this.videoGateway.updateVideo(input.id, userInfo.id, input.title, input.description)

return {
message: `Video ${input.title} updated Successfully!`
Expand Down
19 changes: 10 additions & 9 deletions 21-22-semana/futuretube/backend/src/data/userDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,11 @@ export class UserDB extends BaseDB implements UserGateway{
)
}

private mapDateToDbDate(input: Date): string {
const year = input.getFullYear();
const month = input.getMonth() + 1;
const date = input.getDate();
return `${year + "-" + month + "-" + date}`;
}

public async getUserById(id: string, email: string): Promise<User | undefined>{
public async getUserById(id: string): Promise<User | undefined>{
const result = await this.connection.raw(`
SELECT *
FROM ${this.userTableName}
WHERE id = '${id}' AND email = '${email}'
WHERE id = '${id}'
`)

if(!result[0][0]){
Expand All @@ -56,6 +49,14 @@ export class UserDB extends BaseDB implements UserGateway{
`)
}

public async updatePassword(id: string, password: string): Promise<void>{
await this.connection.raw(`
UPDATE ${this.userTableName}
SET password = '${password}'
WHERE id = '${id}'
`)
}

public async login(email: string): Promise<User | undefined>{
const user = await this.connection.raw(`
SELECT *
Expand Down
11 changes: 5 additions & 6 deletions 21-22-semana/futuretube/backend/src/data/videoDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,19 +75,18 @@ export class VideoDB extends BaseDB implements VideoGateway{
`);
};


public async deleteVideo(id: string): Promise<void>{
public async deleteVideo(id: string, user_id: string): Promise<void>{
await this.connection.raw(`
DELETE FROM ${this.videoTableName}
WHERE id = '${id}';
WHERE id = '${id}' AND user_id = '${user_id}';
`)
}

public async updateVideo(id: string, title: string, description: string): Promise<void>{
public async updateVideo(id: string, user_id: string, title: string, description: string): Promise<void>{
await this.connection.raw(`
UPDATE ${this.videoTableName}
SET title = '${title}', description = '${description}'
WHERE id = '${id}'
WHERE id = '${id}' AND user_id = '${user_id}'
`)
}

Expand Down Expand Up @@ -120,7 +119,7 @@ export class VideoDB extends BaseDB implements VideoGateway{
});
};

public async getVideoByUser(id: string): Promise<Feed[] | undefined>{
public async getAllUserVideos(id: string): Promise<Feed[] | undefined>{
const result = await this.connection.raw(`
SELECT v.*, u.name
FROM ${this.videoTableName} v
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Request, Response } from "express";
import { UpdatePasswordUC } from "../../../business/usecase/user/updatePassword";
import { UserDB } from "../../../data/userDatabase";
import { JwtAuthorizer } from "../../lambda/services/jwtAuthorizer";
import { BcryptService } from "../../lambda/services/bcryptServices";

export const UpdatePasswordEndpoint = async (req: Request, res: Response) => {
try {

const oldPassword = req.body.oldPassword;
const newPassword = req.body.newPassword;
const token = req.headers.auth as string;

if(oldPassword === newPassword){
throw new Error("You cannot use the last same password!")
}

const updatePasswordUC = new UpdatePasswordUC(new UserDB(), new JwtAuthorizer(), new BcryptService());
const result = await updatePasswordUC.execute({
token,
oldPassword,
newPassword
})

res.status(200).send(result)
} catch(err) {
res.status(400).send({
message: err.message
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const DeleteVideoEndpoint = async (req: Request, res: Response) => {
const deleteVideoUC = new DeleteVideoUC(new VideoDB(), new JwtAuthorizer());
const result = await deleteVideoUC.execute({
token: req.headers.auth as string,
id: req.query.id
id: req.params.id
})

res.status(200).send(result)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { Request, Response } from "express";
import { GetVideoByUserUC } from "../../../business/usecase/video/getVideoByUser";
import { GetAllUserVideosUC } from "../../../business/usecase/video/getAllUserVideos";
import { VideoDB } from "../../../data/videoDatabase";
import { JwtAuthorizer } from "../../lambda/services/jwtAuthorizer";

export const GetVideoByUserEndpoint = async (req: Request, res: Response) => {
export const GetAllUserVideosEndpoint = async (req: Request, res: Response) => {
try{
const getVideoByUserUC = new GetVideoByUserUC(new VideoDB, new JwtAuthorizer())
const result = await getVideoByUserUC.execute({

const getAllUserVideosUC = new GetAllUserVideosUC(new VideoDB, new JwtAuthorizer())
const result = await getAllUserVideosUC.execute({
token: req.headers.auth as string,
id: req.query.id
id: req.query ? req.query.id : ""
})

res.status(200).send(result)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const GetVideoDetailEndpoint = async (req: Request, res: Response) => {
try {
const getVideoDetailuc = new GetVideoDetailUC(new VideoDB());
const result = await getVideoDetailuc.execute({
id: req.query.id
id: req.params.id
})

res.status(200).send(result)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const UpdateVideoEndpoint = async (req: Request, res: Response) => {
const updateVideoUC = new UpdateVideoUC(new VideoDB(), new JwtAuthorizer());
const result = await updateVideoUC.execute({
token: req.headers.auth as string,
id: req.query.id,
id: req.params.id,
title: req.body.title,
description: req.body.description
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ export const handler = async (event: LambdaEvent): Promise<any> => {
const response = {
statusCode: err.statusCode || 400,
body: JSON.stringify({
message: err.message || "An unknown error occured"
})
message: err.data
? err.data.message
: err.message || "An unknown error occured",
}),
};
console.log("Error output: ", response);

Expand Down
29 changes: 7 additions & 22 deletions 21-22-semana/futuretube/backend/src/presentation/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { GetAllUsersEndpoint } from "./endpoints/user/getAllUsers";
import { DeleteVideoEndpoint } from "./endpoints/video/deleteVideo";
import { UpdateVideoEndpoint } from "./endpoints/video/updateVideo";
import { GetVideoDetailEndpoint } from "./endpoints/video/getVideoDetail";
import { GetVideoByUserEndpoint } from "./endpoints/video/getVideoByUser";
import { GetAllUserVideosEndpoint } from "./endpoints/video/getAllUserVideos";
import { UpdatePasswordEndpoint } from "./endpoints/user/updatePassword";

const app = express();
app.use(express.json()); // Linha mágica (middleware)
Expand All @@ -16,30 +17,14 @@ app.use(express.json()); // Linha mágica (middleware)
app.post("/signup", SignUpEndpoint);
app.get("/login", LoginEndpoint);
app.get("/users", GetAllUsersEndpoint);
app.post("/updatePassword", UpdatePasswordEndpoint);

// video
app.post("/createVideo", CreateVideoEndpoint);
app.get("/feed", FeedOfVideosEndpoint)
app.delete("/deleteVideo", DeleteVideoEndpoint);
app.post("/updateVideo", UpdateVideoEndpoint);
app.get("/getVideoDetail", GetVideoDetailEndpoint);
app.get("/getVideoByUser", GetVideoByUserEndpoint);

app.get('/', (req: Request, res: Response) => {
const resposta = {
endpoints: {
'/': 'Retorna lista com todos os endpoints',
'/signup': 'Criação dos usuários',
'/login': 'Login do usuário',
'/users': 'Retorna todos usuários. Apenas administradores podem usar esse endpoint',
'/createVideo': 'Cria um video',
'/feed': 'Mostra todos videos',
'/deleteVideo': 'Deleta um vídeo ao passar um id no body',
'/updateVideo': 'Atualiza um video ao passar o id e os dados no body',
'/getVideoByUser/:id': 'pega todos videos de um usuário específico'
}
};
res.send(resposta)
});
app.delete("/deleteVideo/:id", DeleteVideoEndpoint);
app.post("/updateVideo/:id", UpdateVideoEndpoint);
app.get("/getVideoDetail/:id", GetVideoDetailEndpoint);
app.get("/getAllUserVideos", GetAllUserVideosEndpoint);

export default app;
Loading