feat(auth): add user update and delete methods in auth service

This commit adds methods for updating and deleting users in the auth service. Additionally, it includes corresponding validation schemas in the auth schema file. The auth controller code has also been cleaned up for better readability.
This commit is contained in:
Mathis H (Avnyr) 2024-07-11 14:58:34 +02:00
parent 6fb474172a
commit f681dd77bd
Signed by: Mathis
GPG Key ID: DD9E0666A747D126
5 changed files with 100 additions and 34 deletions

View File

@ -2,23 +2,20 @@ import { Body, Controller, HttpCode, HttpStatus, Post } from "@nestjs/common";
import { SignUpDto } from "src/auth/auth.dto";
import { AuthService } from "src/auth/auth.service";
@Controller('auth')
@Controller("auth")
export class AuthController {
constructor(private readonly authService: AuthService) {
}
constructor(private readonly authService: AuthService) {}
//POST signup
@HttpCode(HttpStatus.CREATED)
@Post("signup")
async signUp(@Body() dto: SignUpDto) {
console.log(dto)
return this.authService.doRegister(dto)
}
//POST signup
@HttpCode(HttpStatus.CREATED)
@Post("signup")
async signUp(@Body() dto: SignUpDto) {
console.log(dto);
return this.authService.doRegister(dto);
}
//POST signin
//GET me -- Get current user data via jwt
//DELETE me
//PATCH me
//POST signin
//GET me -- Get current user data via jwt
//DELETE me
//PATCH me
}

View File

@ -47,4 +47,4 @@ export class SignInDto {
minSymbols: 1,
})
password: string;
}
}

View File

@ -29,3 +29,9 @@ export const SignInBodySchema = z.object({
.min(6)
.max(32),
});
export const UserUpdateSchema = z.object({
firstName: z.string({ message: "'firstName' should be a string." }).max(24),
lastName: z.string({ message: "'lastName' should be a string." }).max(24),
});

View File

@ -1,15 +1,15 @@
import * as console from "node:console";
import {
Injectable,
OnModuleInit,
UnauthorizedException,
} from "@nestjs/common";
import { eq } from "drizzle-orm";
import { SignUpBodySchema } from "src/auth/auth.schema";
import { SignInDto, SignUpDto } from "src/auth/auth.dto";
import { UserUpdateSchema } from "src/auth/auth.schema";
import { CredentialsService } from "src/credentials/credentials.service";
import { DrizzleService } from "src/drizzle/drizzle.service";
import { UsersTable } from "src/schema";
import { SignInDto, SignUpDto } from "src/auth/auth.dto";
import { IUserUpdateData } from "src/auth/auth.types";
@Injectable()
export class AuthService implements OnModuleInit {
@ -49,32 +49,91 @@ export class AuthService implements OnModuleInit {
});
return {
message: "User created, check your email for validation.",
token: await this.credentials.signAuthToken({sub: query[0].uuid})
}
token: await this.credentials.signAuthToken({ sub: query[0].uuid }),
};
}
doLogin(data: SignInDto) {}
async doLogin(data: SignInDto) {
const user = await this.db
.use()
.select()
.from(UsersTable)
.where(eq(UsersTable.email, data.email))
.prepare("userByEmail")
.execute();
if (user.length !== 1)
throw new UnauthorizedException("Invalid credentials");
const passwordMatch = await this.credentials.check(
data.password,
user[0].hash,
);
if (!passwordMatch) throw new UnauthorizedException("Invalid credentials");
const token = await this.credentials.signAuthToken({ sub: user[0].uuid });
return {
message: "Login successful",
token: token,
};
}
async fetchUser(userId: string) {
//TODO Pagination
const usersInDb = await this.db.use().select().from(UsersTable);
const result = {
total: usersInDb.length,
users: usersInDb.map((user)=>{
delete user.hash
users: usersInDb.map((user) => {
delete user.hash;
return {
...user
}
})
}
console.log(result)
...user,
};
}),
};
console.log(result);
}
async updateUser(targetId: string, userData: IUserUpdateData) {
const validationResult = UserUpdateSchema.safeParse(userData);
if (!validationResult.success) {
throw new UnauthorizedException(validationResult.error);
}
const updateQuery = await this.db
.use()
.update(UsersTable)
.set({
...userData
})
.where(eq(UsersTable.uuid, targetId))
.prepare("updateUserById")
.execute()
.catch((err) => {
console.error(err);
throw new UnauthorizedException(
"Error occurred while updating user",
err,
);
});
return true;
}
async deleteUser(targetId: string) {
await this.db
.use()
.delete(UsersTable)
.where(eq(UsersTable.uuid, targetId))
.prepare("deleteUserById")
.execute()
.catch((err) => {
console.error(err);
throw new UnauthorizedException(
"Error occurred while deleting user",
err,
);
});
return true;
}
updateUser() {}
deleteUser() {}
async onModuleInit() {
setTimeout(()=>{
setTimeout(() => {
this.fetchUser("ee");
}, 2000)
}, 2000);
}
}

4
src/auth/auth.types.ts Normal file
View File

@ -0,0 +1,4 @@
export interface IUserUpdateData {
firstName?: string;
lastName?: string;
}