correciones de compilacion
This commit is contained in:
@@ -4,8 +4,8 @@ import { Env, validateString } from '@/common/utils';
|
|||||||
import { DRIZZLE_PROVIDER } from '@/database/drizzle-provider';
|
import { DRIZZLE_PROVIDER } from '@/database/drizzle-provider';
|
||||||
import { RefreshTokenDto } from '@/features/auth/dto/refresh-token.dto';
|
import { RefreshTokenDto } from '@/features/auth/dto/refresh-token.dto';
|
||||||
import { SignInUserDto } from '@/features/auth/dto/signIn-user.dto';
|
import { SignInUserDto } from '@/features/auth/dto/signIn-user.dto';
|
||||||
import { SingUpUserDto } from '@/features/auth/dto/signUp-user.dto';
|
|
||||||
import { SignOutUserDto } from '@/features/auth/dto/signOut-user.dto';
|
import { SignOutUserDto } from '@/features/auth/dto/signOut-user.dto';
|
||||||
|
import { SingUpUserDto } from '@/features/auth/dto/signUp-user.dto';
|
||||||
import { ValidateUserDto } from '@/features/auth/dto/validate-user.dto';
|
import { ValidateUserDto } from '@/features/auth/dto/validate-user.dto';
|
||||||
import AuthTokensInterface from '@/features/auth/interfaces/auth-tokens.interface';
|
import AuthTokensInterface from '@/features/auth/interfaces/auth-tokens.interface';
|
||||||
import {
|
import {
|
||||||
@@ -24,14 +24,14 @@ import {
|
|||||||
UnauthorizedException,
|
UnauthorizedException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { JwtService } from '@nestjs/jwt';
|
import { JwtService, JwtSignOptions } from '@nestjs/jwt';
|
||||||
|
import * as bcrypt from 'bcryptjs';
|
||||||
import crypto from 'crypto';
|
import crypto from 'crypto';
|
||||||
import { and, eq, or } from 'drizzle-orm';
|
import { and, eq, or } from 'drizzle-orm';
|
||||||
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
||||||
import * as schema from 'src/database/index';
|
import * as schema from 'src/database/index';
|
||||||
import { sessions, users, roles, usersRole } from 'src/database/index';
|
import { roles, sessions, users, usersRole } from 'src/database/index';
|
||||||
import { Session } from './interfaces/session.interface';
|
import { Session } from './interfaces/session.interface';
|
||||||
import * as bcrypt from 'bcryptjs';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
@@ -81,33 +81,43 @@ export class AuthService {
|
|||||||
|
|
||||||
//Generate Tokens
|
//Generate Tokens
|
||||||
async generateTokens(user: User): Promise<AuthTokensInterface> {
|
async generateTokens(user: User): Promise<AuthTokensInterface> {
|
||||||
|
const accessTokenSecret = envs.access_token_secret ?? '';
|
||||||
|
const accessTokenExp = envs.access_token_expiration ?? '';
|
||||||
|
const refreshTokenSecret = envs.refresh_token_secret ?? '';
|
||||||
|
const refreshTokenExp = envs.refresh_token_expiration ?? '';
|
||||||
|
|
||||||
|
if (
|
||||||
|
!accessTokenSecret ||
|
||||||
|
!accessTokenExp ||
|
||||||
|
!refreshTokenSecret ||
|
||||||
|
!refreshTokenExp
|
||||||
|
) {
|
||||||
|
throw new Error('JWT environment variables are missing or invalid');
|
||||||
|
}
|
||||||
|
|
||||||
|
interface JwtPayload {
|
||||||
|
sub: number;
|
||||||
|
username: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload: JwtPayload = {
|
||||||
|
sub: Number(user?.id),
|
||||||
|
username: user.username ?? '',
|
||||||
|
};
|
||||||
|
|
||||||
const [access_token, refresh_token] = await Promise.all([
|
const [access_token, refresh_token] = await Promise.all([
|
||||||
this.jwtService.signAsync(
|
this.jwtService.signAsync(payload, {
|
||||||
{
|
secret: accessTokenSecret,
|
||||||
sub: user.id,
|
expiresIn: accessTokenExp,
|
||||||
username: user.username,
|
} as JwtSignOptions),
|
||||||
},
|
|
||||||
{
|
this.jwtService.signAsync(payload, {
|
||||||
secret: envs.access_token_secret,
|
secret: refreshTokenSecret,
|
||||||
expiresIn: envs.access_token_expiration,
|
expiresIn: refreshTokenExp,
|
||||||
},
|
} as JwtSignOptions),
|
||||||
),
|
|
||||||
this.jwtService.signAsync(
|
|
||||||
{
|
|
||||||
sub: user.id,
|
|
||||||
username: user.username,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
secret: envs.refresh_token_secret,
|
|
||||||
expiresIn: envs.refresh_token_expiration,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return {
|
return { access_token, refresh_token };
|
||||||
access_token,
|
|
||||||
refresh_token,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//Generate OTP Code For Email Confirmation
|
//Generate OTP Code For Email Confirmation
|
||||||
@@ -138,7 +148,8 @@ export class AuthService {
|
|||||||
userId: parseInt(userId),
|
userId: parseInt(userId),
|
||||||
expiresAt: sessionInput.expiresAt,
|
expiresAt: sessionInput.expiresAt,
|
||||||
});
|
});
|
||||||
if (session.rowCount === 0) throw new HttpException('Failed to create session', HttpStatus.NOT_FOUND);
|
if (session.rowCount === 0)
|
||||||
|
throw new HttpException('Failed to create session', HttpStatus.NOT_FOUND);
|
||||||
|
|
||||||
return 'Session created successfully';
|
return 'Session created successfully';
|
||||||
}
|
}
|
||||||
@@ -197,7 +208,6 @@ export class AuthService {
|
|||||||
|
|
||||||
//Sign In User Account
|
//Sign In User Account
|
||||||
async signIn(dto: SignInUserDto): Promise<LoginUserInterface> {
|
async signIn(dto: SignInUserDto): Promise<LoginUserInterface> {
|
||||||
|
|
||||||
const user = await this.validateUser(dto);
|
const user = await this.validateUser(dto);
|
||||||
const tokens = await this.generateTokens(user);
|
const tokens = await this.generateTokens(user);
|
||||||
const decodeAccess = this.decodeToken(tokens.access_token);
|
const decodeAccess = this.decodeToken(tokens.access_token);
|
||||||
@@ -265,12 +275,12 @@ export class AuthService {
|
|||||||
async refreshToken(dto: RefreshTokenDto): Promise<RefreshTokenInterface> {
|
async refreshToken(dto: RefreshTokenDto): Promise<RefreshTokenInterface> {
|
||||||
const secret = envs.refresh_token_secret;
|
const secret = envs.refresh_token_secret;
|
||||||
const { user_id, token } = dto;
|
const { user_id, token } = dto;
|
||||||
|
|
||||||
console.log('secret', secret);
|
console.log('secret', secret);
|
||||||
console.log('refresh_token', token);
|
console.log('refresh_token', token);
|
||||||
|
|
||||||
const validation = await this.jwtService.verifyAsync(token, {
|
const validation = await this.jwtService.verifyAsync(token, {
|
||||||
secret
|
secret,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!validation) throw new UnauthorizedException('Invalid refresh token');
|
if (!validation) throw new UnauthorizedException('Invalid refresh token');
|
||||||
@@ -279,23 +289,20 @@ export class AuthService {
|
|||||||
.select()
|
.select()
|
||||||
.from(sessions)
|
.from(sessions)
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(eq(sessions.userId, user_id), eq(sessions.sessionToken, token)),
|
||||||
eq(sessions.userId, user_id),
|
|
||||||
eq(sessions.sessionToken, token)
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// console.log(session.length);
|
// console.log(session.length);
|
||||||
|
|
||||||
if (session.length === 0) throw new NotFoundException('session not found');
|
if (session.length === 0) throw new NotFoundException('session not found');
|
||||||
const user = await this.findUserById(user_id);
|
const user = await this.findUserById(user_id);
|
||||||
if (!user) throw new NotFoundException('User not found');
|
if (!user) throw new NotFoundException('User not found');
|
||||||
|
|
||||||
// Genera token
|
// Genera token
|
||||||
const tokens = await this.generateTokens(user);
|
const tokens = await this.generateTokens(user);
|
||||||
const decodeAccess = this.decodeToken(tokens.access_token);
|
const decodeAccess = this.decodeToken(tokens.access_token);
|
||||||
const decodeRefresh = this.decodeToken(tokens.refresh_token);
|
const decodeRefresh = this.decodeToken(tokens.refresh_token);
|
||||||
|
|
||||||
// Actualiza session
|
// Actualiza session
|
||||||
await this.drizzle
|
await this.drizzle
|
||||||
.update(sessions)
|
.update(sessions)
|
||||||
@@ -311,75 +318,82 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async singUp(createUserDto: SingUpUserDto): Promise<User> {
|
async singUp(createUserDto: SingUpUserDto): Promise<User> {
|
||||||
// Check if username or email exists
|
// Check if username or email exists
|
||||||
const data = await this.drizzle
|
const data = await this.drizzle
|
||||||
|
.select({
|
||||||
|
id: users.id,
|
||||||
|
username: users.username,
|
||||||
|
email: users.email,
|
||||||
|
})
|
||||||
|
.from(users)
|
||||||
|
.where(
|
||||||
|
or(
|
||||||
|
eq(users.username, createUserDto.username),
|
||||||
|
eq(users.email, createUserDto.email),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (data.length > 0) {
|
||||||
|
if (data[0].username === createUserDto.username) {
|
||||||
|
throw new HttpException(
|
||||||
|
'Username already exists',
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (data[0].email === createUserDto.email) {
|
||||||
|
throw new HttpException('Email already exists', HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash the password
|
||||||
|
const hashedPassword = await bcrypt.hash(createUserDto.password, 10);
|
||||||
|
|
||||||
|
// Start a transaction
|
||||||
|
return await this.drizzle.transaction(async (tx) => {
|
||||||
|
// Create the user
|
||||||
|
const [newUser] = await tx
|
||||||
|
.insert(users)
|
||||||
|
.values({
|
||||||
|
username: createUserDto.username,
|
||||||
|
email: createUserDto.email,
|
||||||
|
password: hashedPassword,
|
||||||
|
fullname: createUserDto.fullname,
|
||||||
|
isActive: true,
|
||||||
|
state: createUserDto.state,
|
||||||
|
municipality: createUserDto.municipality,
|
||||||
|
parish: createUserDto.parish,
|
||||||
|
phone: createUserDto.phone,
|
||||||
|
isEmailVerified: false,
|
||||||
|
isTwoFactorEnabled: false,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
// check if user role is admin
|
||||||
|
const role = createUserDto.role <= 2 ? 5 : createUserDto.role;
|
||||||
|
|
||||||
|
// Assign role to user
|
||||||
|
await tx.insert(usersRole).values({
|
||||||
|
userId: newUser.id,
|
||||||
|
roleId: role,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return the created user with role
|
||||||
|
const [userWithRole] = await tx
|
||||||
.select({
|
.select({
|
||||||
id: users.id,
|
id: users.id,
|
||||||
username: users.username,
|
username: users.username,
|
||||||
email: users.email
|
email: users.email,
|
||||||
|
fullname: users.fullname,
|
||||||
|
phone: users.phone,
|
||||||
|
isActive: users.isActive,
|
||||||
|
role: roles.name,
|
||||||
})
|
})
|
||||||
.from(users)
|
.from(users)
|
||||||
.where(or(eq(users.username, createUserDto.username), eq(users.email, createUserDto.email)));
|
.leftJoin(usersRole, eq(usersRole.userId, users.id))
|
||||||
|
.leftJoin(roles, eq(roles.id, usersRole.roleId))
|
||||||
if (data.length > 0) {
|
.where(eq(users.id, newUser.id));
|
||||||
if (data[0].username === createUserDto.username) {
|
|
||||||
throw new HttpException('Username already exists', HttpStatus.BAD_REQUEST);
|
|
||||||
}
|
|
||||||
if (data[0].email === createUserDto.email) {
|
|
||||||
throw new HttpException('Email already exists', HttpStatus.BAD_REQUEST);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hash the password
|
return userWithRole;
|
||||||
const hashedPassword = await bcrypt.hash(createUserDto.password, 10);
|
});
|
||||||
|
|
||||||
// Start a transaction
|
|
||||||
return await this.drizzle.transaction(async (tx) => {
|
|
||||||
// Create the user
|
|
||||||
const [newUser] = await tx
|
|
||||||
.insert(users)
|
|
||||||
.values({
|
|
||||||
username: createUserDto.username,
|
|
||||||
email: createUserDto.email,
|
|
||||||
password: hashedPassword,
|
|
||||||
fullname: createUserDto.fullname,
|
|
||||||
isActive: true,
|
|
||||||
state: createUserDto.state,
|
|
||||||
municipality: createUserDto.municipality,
|
|
||||||
parish: createUserDto.parish,
|
|
||||||
phone: createUserDto.phone,
|
|
||||||
isEmailVerified: false,
|
|
||||||
isTwoFactorEnabled: false,
|
|
||||||
})
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
// check if user role is admin
|
|
||||||
const role = createUserDto.role <= 2 ? 5 : createUserDto.role;
|
|
||||||
|
|
||||||
// Assign role to user
|
|
||||||
await tx.insert(usersRole).values({
|
|
||||||
userId: newUser.id,
|
|
||||||
roleId: role,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Return the created user with role
|
|
||||||
const [userWithRole] = await tx
|
|
||||||
.select({
|
|
||||||
id: users.id,
|
|
||||||
username: users.username,
|
|
||||||
email: users.email,
|
|
||||||
fullname: users.fullname,
|
|
||||||
phone: users.phone,
|
|
||||||
isActive: users.isActive,
|
|
||||||
role: roles.name,
|
|
||||||
})
|
|
||||||
.from(users)
|
|
||||||
.leftJoin(usersRole, eq(usersRole.userId, users.id))
|
|
||||||
.leftJoin(roles, eq(roles.id, usersRole.roleId))
|
|
||||||
.where(eq(users.id, newUser.id));
|
|
||||||
|
|
||||||
return userWithRole;
|
|
||||||
})
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
'use client';
|
'use client';
|
||||||
import { DataTable } from '@repo/shadcn/table/data-table';
|
import { DataTable } from '@repo/shadcn/table/data-table';
|
||||||
import { DataTableSkeleton } from '@repo/shadcn/table/data-table-skeleton';
|
import { DataTableSkeleton } from '@repo/shadcn/table/data-table-skeleton';
|
||||||
import { columns } from './product-tables/columns';
|
|
||||||
import { useProductQuery } from '../../hooks/use-query-products';
|
import { useProductQuery } from '../../hooks/use-query-products';
|
||||||
|
import { columns } from './product-tables/columns';
|
||||||
|
|
||||||
interface dataListProps {
|
interface dataListProps {
|
||||||
initialPage: number;
|
initialPage: number;
|
||||||
initialSearch?: string | null;
|
initialSearch?: string | null;
|
||||||
initialLimit: number;
|
initialLimit: number;
|
||||||
|
initialType?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function UsersAdminList({
|
export default function UsersAdminList({
|
||||||
@@ -19,9 +20,9 @@ export default function UsersAdminList({
|
|||||||
page: initialPage,
|
page: initialPage,
|
||||||
limit: initialLimit,
|
limit: initialLimit,
|
||||||
...(initialSearch && { search: initialSearch }),
|
...(initialSearch && { search: initialSearch }),
|
||||||
}
|
};
|
||||||
|
|
||||||
const {data, isLoading} = useProductQuery(filters)
|
const { data, isLoading } = useProductQuery(filters);
|
||||||
|
|
||||||
// console.log(data?.data);
|
// console.log(data?.data);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user