Skip to content

Commit

Permalink
DEV - DELETE user impacts on code + http errors + logout deleted user
Browse files Browse the repository at this point in the history
  • Loading branch information
juliecoust committed Jan 30, 2024
1 parent c168ead commit 770949b
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 90 deletions.
2 changes: 0 additions & 2 deletions src/domain/use-cases/auth/refresh-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ export class RefreshToken implements RefreshTokenUseCase {
}

async execute(userAuth: DecodedToken): Promise<AuthJwtRefreshedResponseModel> {
// User should not be deleted
if (await this.userRepository.isDeleted(userAuth.user_id)) throw new Error("User is deleted");

// Get full user based on decoded token user's email
const full_user = await this.userRepository.getUser({ email: userAuth.email })
Expand Down
1 change: 0 additions & 1 deletion src/domain/use-cases/user/delete-user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ export class DeleteUser implements DeleteUserUseCase {
}

const updated_user = await this.userRepository.getUser({ user_id: user_to_update.user_id })
console.log(updated_user)
if (!updated_user) throw new Error("Can't find deleted user");

}
Expand Down
1 change: 0 additions & 1 deletion src/presentation/middleware/auth-cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ export class MiddlewareAuthCookie implements MiddlewareAuth {
// If token is missing, send a 401 Unauthorized response
if (!token) return res.status(401).send({ errors: ['Refresh token missing. Please authenticate.'] })


// Verify the token using the refresh secret key
const decoded = this.jwt.verify(token, this.SECRET_KEY_REFRESH);

Expand Down
7 changes: 6 additions & 1 deletion src/presentation/routers/auth-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,15 @@ export default function AuthRouter(
} catch (err) {
console.log(err)
if (err.message === "Invalid credentials") res.status(401).send({ errors: [err.message] })
else if (err.message === "User is deleted") res.status(403).send({ errors: [err.message] })
else if (err.message === "User email not verified") res.status(403).send({ errors: [err.message] })
else res.status(500).send({ errors: ["Can't login"] })
}
})

router.get('/user/me', middlewareAuth.auth, async (req: Request, res: Response) => {
try {
// TODO check if user valid?
// TODO check if user valid
res.status(200).send((req as CustomRequest).token)
} catch (err) {
console.log(err.message)
Expand All @@ -66,6 +67,7 @@ export default function AuthRouter(
} catch (err) {
console.log(err)
if (err.message === "Can't find user") res.status(404).send({ errors: [err.message] })
else if (err.message === "User is deleted") res.status(403).send({ errors: [err.message] })
else res.status(500).send({ errors: ["Can't refresh token"] })
}
})
Expand Down Expand Up @@ -97,6 +99,7 @@ export default function AuthRouter(
} catch (err) {
console.log(err)
if (err.message === "New password must be different from old password") res.status(401).send({ errors: ["New password must be different from old password"] })
else if (err.message === "User is deleted") res.status(403).send({ errors: [err.message] })
else res.status(500).send({ errors: ["Can't change password"] })
}
})
Expand All @@ -111,6 +114,7 @@ export default function AuthRouter(
} catch (err) {
console.log(err)
if (err.message === "User does not exist") res.status(200).send({ response: "Reset password request email sent." })
else if (err.message === "User is deleted") res.status(403).send({ errors: [err.message] })
else if (err.message === "User email is not validated") res.status(200).send({ response: "Reset password request email sent." })
else if (err.message === "Can't set password reset code") res.status(500).send({ errors: ["Can't reset password"] })
else if (err.message === "Can't find updated user") res.status(500).send({ errors: ["Can't reset password"] })
Expand All @@ -128,6 +132,7 @@ export default function AuthRouter(
} catch (err) {
console.log(err)
if (err.message === "Token is not valid") res.status(401).send({ errors: ["Can't reset password"] })
else if (err.message === "User is deleted") res.status(403).send({ errors: [err.message] })
else if (err.message === "No token provided") res.status(401).send({ errors: ["Can't reset password"] })
else if (err.message === "User does not exist or reset_password_code is not valid") res.status(404).send({ errors: ["Can't reset password"] })
else if (err.message === "User email is not validated") res.status(403).send({ errors: ["Can't reset password"] })
Expand Down
15 changes: 13 additions & 2 deletions src/presentation/routers/user-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export default function UsersRouter(
} catch (err) {
console.log(err)
if (err.message === "Valid user already exist") res.status(403).send({ errors: ["Can't create user"] })
else if (err.message === "User is deleted") res.status(403).send({ errors: [err.message] })
else if (err.message === "Can't update preexistent user") res.status(403).send({ errors: [err.message] })
else if (err.message === "Can't find updated preexistent user") res.status(404).send({ errors: [err.message] })
else if (err.message === "Can't find created user") res.status(404).send({ errors: [err.message] })
Expand All @@ -52,6 +53,7 @@ export default function UsersRouter(
} catch (err) {
console.log(err)
if (err.message === "Logged user cannot update this property or user") res.status(401).send({ errors: [err.message] })
else if (err.message === "User is deleted") res.status(403).send({ errors: [err.message] })
else if (err.message === "Can't find updated user") res.status(404).send({ errors: [err.message] })
else res.status(500).send({ errors: ["Can't update user"] })
}
Expand All @@ -67,6 +69,7 @@ export default function UsersRouter(
} catch (err) {
console.log(err)
if (err.message === "Invalid confirmation token") res.status(401).send({ errors: [err.message] })
else if (err.message === "User is deleted") res.status(403).send({ errors: [err.message] })
else if (err.message === "Invalid confirmation code") res.status(401).send({ errors: [err.message] })
else if (err.message === "User vallidation forbidden") res.status(403).send({ errors: [err.message] })
else if (err.message === "Can't update user") res.status(500).send({ errors: [err.message] })
Expand All @@ -78,12 +81,20 @@ export default function UsersRouter(

router.delete('/:user_id/', middlewareAuth.auth, async (req: Request, res: Response) => {
try {
const deleted_user = await deleteUserUseCase.execute((req as CustomRequest).token, { ...req.body, user_id: req.params.user_id })
res.status(200).send(deleted_user)
await deleteUserUseCase.execute((req as CustomRequest).token, { ...req.body, user_id: req.params.user_id })
if ((req as CustomRequest).token.user_id == parseInt(req.params.user_id)) {
res
.clearCookie("access_token")
.clearCookie("refresh_token")
.status(200)
.json({ response: "You have been Logged Out and permanently deleted" });
} else
res.status(200).send({ message: "User successfully deleted" })
} catch (err) {
console.log(err)
if (err.message === "Logged user cannot delete this user") res.status(401).send({ errors: [err.message] })
else if (err.message === "Can't find user to delete") res.status(404).send({ errors: [err.message] })
else if (err.message === "User is deleted") res.status(403).send({ errors: [err.message] })
else if (err.message === "Can't find deleted user") res.status(500).send({ errors: [err.message] })
else res.status(500).send({ errors: ["Can't delete user"] })
}
Expand Down
160 changes: 77 additions & 83 deletions test/data/data-sources/sqlite/sqlite-user-data-source.test.todo.ts
Original file line number Diff line number Diff line change
@@ -1,97 +1,91 @@
import { SQLiteUserDataSource } from '../../../../src/data/data-sources/sqlite/sqlite-user-data-source'
import { SQLiteDatabaseWrapper } from '../../../../src/data/interfaces/data-sources/database-wrapper';
import { UserRequesCreationtModel, UserResponseModel } from '../../../../src/domain/entities/user';
// import { SQLiteUserDataSource } from '../../../../src/data/data-sources/sqlite/sqlite-user-data-source'
// import { SQLiteDatabaseWrapper } from '../../../../src/data/interfaces/data-sources/database-wrapper';
// import { UserRequesCreationtModel, UserResponseModel } from '../../../../src/domain/entities/user';

// TODO COMPLETE TESTS
describe("PG DataSource", () => {
// // TODO COMPLETE TESTS
// describe("PG DataSource", () => {

let mockDatabase: SQLiteDatabaseWrapper
// let mockDatabase: SQLiteDatabaseWrapper

beforeAll(async () => {
mockDatabase = {
all: jest.fn(),
run: jest.fn(),
get: jest.fn(),
// beforeAll(async () => {
// mockDatabase = {
// all: jest.fn(),
// run: jest.fn(),
// get: jest.fn(),

}
})
// }
// })

beforeEach(() => {
jest.clearAllMocks();
})
// beforeEach(() => {
// jest.clearAllMocks();
// })

// TODO : AUTO ID
test("getAll", async () => {
const OutputData: UserResponseModel = {
user_id: 1,
last_name: "Smith",
first_name: "John",
email: "[email protected]",
is_admin: false,
valid_email: true,
organisation: "LOV",
country: "France",
user_planned_usage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
user_creation_date: '2023-08-01 10:30:00'
}
const DbOutputData = {
user_id: 1,
last_name: "Smith",
first_name: "John",
email: "[email protected]",
is_admin: 0,
valid_email: 1,
organisation: "LOV",
country: "France",
user_planned_usage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
user_creation_date: '2023-08-01 10:30:00'
}
const ds = new SQLiteUserDataSource(mockDatabase);
jest.spyOn(mockDatabase, "all").mockImplementation(() => Promise.resolve({ rows: [{ name: "Smith", user_id: "123" }] }))
const result = await ds.getAll();
expect(mockDatabase.all).toHaveBeenCalledWith("SELECT * FROM user")
expect(result).toStrictEqual([OutputData])
})
// // TODO : AUTO ID
// test("getAll", async () => {
// const OutputData: UserResponseModel = {
// user_id: 1,
// last_name: "Smith",
// first_name: "John",
// email: "[email protected]",
// is_admin: false,
// valid_email: true,
// organisation: "LOV",
// country: "France",
// user_planned_usage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
// user_creation_date: '2023-08-01 10:30:00'
// }
// const DbOutputData = {
// user_id: 1,
// last_name: "Smith",
// first_name: "John",
// email: "[email protected]",
// is_admin: 0,
// valid_email: 1,
// organisation: "LOV",
// country: "France",
// user_planned_usage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
// user_creation_date: '2023-08-01 10:30:00'
// }
// const ds = new SQLiteUserDataSource(mockDatabase);
// jest.spyOn(mockDatabase, "all").mockImplementation(() => Promise.resolve({ rows: [{ name: "Smith", user_id: "123" }] }))
// const result = await ds.getAll();
// expect(mockDatabase.all).toHaveBeenCalledWith("SELECT * FROM user")
// expect(result).toStrictEqual([OutputData])
// })


describe('create method', () => {
test('should insert a user into the database', async () => {
const ds = new SQLiteUserDataSource(mockDatabase);
const inputData: UserRequesCreationtModel = {
last_name: "Smith",
first_name: "John",
email: "[email protected]",
password: "123test!",
organisation: "LOV",
country: "France",
user_planned_usage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
}
await ds.create(inputData);
expect(mockDatabase.run).toHaveBeenCalledWith("INSERT INTO user (name) VALUES ($1)", ["Smith"])
});
// describe('create method', () => {
// test('should insert a user into the database', async () => {
// const ds = new SQLiteUserDataSource(mockDatabase);
// const inputData: UserRequesCreationtModel = {
// last_name: "Smith",
// first_name: "John",
// email: "[email protected]",
// password: "123test!",
// organisation: "LOV",
// country: "France",
// user_planned_usage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
// }
// await ds.create(inputData);
// expect(mockDatabase.run).toHaveBeenCalledWith("INSERT INTO user (name) VALUES ($1)", ["Smith"])
// });


});
// });


// test("deleteOne", async () => {
// const ds = new SQLiteUserDataSource(mockDatabase);
// await ds.deleteOne("1");
// expect(mockDatabase.query).toHaveBeenCalledWith("delete tb_user where user_id = $1", ["1"])
// })
// // test("updateOne", async () => {
// // const ds = new SQLiteUserDataSource(mockDatabase);
// // await ds.updateOne("1", { name: "Ramon" });
// // expect(mockDatabase.query).toHaveBeenCalledWith("update tb_user set name = $1 where user_id = $2", ["Ramon", "1"])
// // })

// test("updateOne", async () => {
// const ds = new SQLiteUserDataSource(mockDatabase);
// await ds.updateOne("1", { name: "Ramon" });
// expect(mockDatabase.query).toHaveBeenCalledWith("update tb_user set name = $1 where user_id = $2", ["Ramon", "1"])
// })
// // test("getOne", async () => {
// // const ds = new SQLiteUserDataSource(mockDatabase);
// // jest.spyOn(mockDatabase, "query").mockImplementation(() => Promise.resolve({ rows: [{ user_id: "123", name: "Smith", }] }))
// // const result = await ds.getOne("123");
// // expect(result).toStrictEqual({ name: "Smith", user_id: "123" })
// // expect(mockDatabase.query).toHaveBeenCalledWith("select * from tb_user where user_id = $1 limit 1", ["123"])
// // })

// test("getOne", async () => {
// const ds = new SQLiteUserDataSource(mockDatabase);
// jest.spyOn(mockDatabase, "query").mockImplementation(() => Promise.resolve({ rows: [{ user_id: "123", name: "Smith", }] }))
// const result = await ds.getOne("123");
// expect(result).toStrictEqual({ name: "Smith", user_id: "123" })
// expect(mockDatabase.query).toHaveBeenCalledWith("select * from tb_user where user_id = $1 limit 1", ["123"])
// })

})
// })

0 comments on commit 770949b

Please sign in to comment.