Add refresh token endpoint for admin and user

master
nicekid1 1 month ago
parent 3591ae9139
commit b043c75f92
  1. 44
      migrations/20250104074851-create-user.js
  2. 13
      migrations/20250104094702-create-admin.js
  3. 10
      src/admin/admin.controller.ts
  4. 48
      src/admin/admin.service.ts
  5. 5
      src/admin/entities/admin.entity.ts
  6. 7
      src/users/entities/user.entity.ts
  7. 8
      src/users/users.controller.ts
  8. 75
      src/users/users.service.ts

@ -1,63 +1,69 @@
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.dropTable('Users',{cascade:true})
up: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Users', { cascade: true });
await queryInterface.createTable('Users', {
id: {
allowNull: false,
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
allowNull: false,
},
email: {
type: Sequelize.STRING,
unique: true,
allowNull: false
allowNull: false,
},
password: {
type: Sequelize.STRING,
allowNull: false
allowNull: false,
},
role: {
type: Sequelize.STRING,
defaultValue: 'user'
allowNull: false,
defaultValue: 'user',
},
firstName: {
type: Sequelize.STRING,
allowNull: false
allowNull: true,
},
lastName: {
type: Sequelize.STRING,
allowNull: false
allowNull: true,
},
username: {
type: Sequelize.STRING,
unique: true,
allowNull: false
allowNull: false,
},
phoneNumber: {
type: Sequelize.STRING,
unique: true,
allowNull: false
allowNull: false,
},
gender: {
type: Sequelize.ENUM("male", "female"),
allowNull: false
type: Sequelize.ENUM('male', 'female'),
allowNull: false,
},
refreshToken: {
type: Sequelize.STRING,
allowNull: true,
},
createdAt: {
type: Sequelize.DATE,
allowNull: false,
type: Sequelize.DATE
defaultValue: Sequelize.fn('NOW'),
},
updatedAt: {
type: Sequelize.DATE,
allowNull: false,
type: Sequelize.DATE
}
defaultValue: Sequelize.fn('NOW'),
},
});
},
async down(queryInterface, Sequelize) {
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Users');
}
},
};

@ -3,13 +3,12 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Admins', { cascade: true });
await queryInterface.createTable('Admins', {
id: {
allowNull: false,
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
allowNull: false,
},
email: {
type: Sequelize.STRING,
@ -42,6 +41,10 @@ module.exports = {
allowNull: false,
unique: true,
},
refreshToken: {
type: Sequelize.STRING,
allowNull: true,
},
gender: {
type: Sequelize.ENUM('male', 'female'),
allowNull: false,
@ -49,12 +52,12 @@ module.exports = {
createdAt: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.NOW,
defaultValue: Sequelize.fn('NOW'),
},
updatedAt: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.NOW,
defaultValue: Sequelize.fn('NOW'),
},
});
},

@ -8,14 +8,22 @@ import { RoleGuard } from "src/guard/role.guard";
@Controller("admin")
export class AdminController {
constructor(private readonly adminService: AdminService) {}
// register as a admin
@Post("register")
async register(@Body() createAdminDto: CreateAdminDto): Promise<{message}> {
return this.adminService.register(createAdminDto);
}
//login as admin
@Post("login")
async login(@Body() loginAdminDto: LoginAdminDto): Promise<{ token: string }> {
async login(@Body() loginAdminDto: LoginAdminDto): Promise<{ accessToken, refreshToken }> {
return this.adminService.login(loginAdminDto);
}
//get a new access token
@Post("new-token")
async newAccessToken(@Body("refreshToken") refreshToken: string) {
return this.adminService.newAccessToken(refreshToken);
}
//edit admin profile
@UseGuards(RoleGuard)
@Put()
async editAdminProfile(@Request() req, @Body() updateAdminDto: UpdateUserDto): Promise<{message}>{

@ -34,7 +34,7 @@ export class AdminService {
}
}
//login method
async login(loginAdminDto: LoginAdminDto): Promise<{ token: string }> {
async login(loginAdminDto: LoginAdminDto): Promise<{ accessToken: string; refreshToken: string }> {
try {
const admin = await this.adminModel.findOne({
where: { email: loginAdminDto.email },
@ -49,7 +49,7 @@ export class AdminService {
throw new HttpException("Invalid email or password.", HttpStatus.UNAUTHORIZED);
}
const token = this.jwtService.sign(
const accessToken = this.jwtService.sign(
{ id: admin.id, role: admin.role },
{
secret: this.configService.get<string>("JWT_SECRET"),
@ -57,7 +57,15 @@ export class AdminService {
},
);
return { token };
const refreshToken = this.jwtService.sign(
{ id: admin.id, role: admin.role },
{
secret: this.configService.get<string>("JWT_REFRESH_SECRET"),
expiresIn: this.configService.get<string | number>("JWT_REFRESH_EXPIRES") || "7d",
},
);
return { accessToken, refreshToken };
} catch (error) {
if (error instanceof HttpException) {
throw error;
@ -65,6 +73,40 @@ export class AdminService {
throw new HttpException("An unexpected error occurred. Please try again later.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
//getting new access token
async newAccessToken(refreshToken: string) {
if (!refreshToken) {
throw new HttpException({ message: "Refresh token is required." }, HttpStatus.BAD_REQUEST);
}
let decoded;
try {
decoded = this.jwtService.verify(refreshToken, { secret: process.env.JWT_REFRESH_SECRET });
} catch (error) {
throw new HttpException({ message: "Invalid or expired token." }, HttpStatus.UNAUTHORIZED);
}
const user = await this.adminModel.findOne({
where: { id: decoded.id },
});
if (!user) {
throw new HttpException({ message: "User not found." }, HttpStatus.NOT_FOUND);
}
if (user.role !== "admin") {
throw new HttpException({ message: "You are not authorized to get an admin token." }, HttpStatus.FORBIDDEN);
}
const accessToken = this.jwtService.sign(
{ id: user.id, role: user.role },
{
secret: this.configService.get<string>("JWT_SECRET"),
expiresIn: this.configService.get<string | number>("JWT_EXPIRES") || "1h",
},
);
return { accessToken };
}
//edit admin profile method
async editAdminProfile(userId: number, updateAdminDto: UpdateUserDto) {
try {

@ -22,6 +22,11 @@ export class Admin extends Model<Admin> {
@Column({ unique: true })
phoneNumber: string;
@Column({
type: DataType.STRING,
allowNull: true,
})
refreshToken: string;
@Column({
type: DataType.ENUM("male", "female"),

@ -28,6 +28,13 @@ export class User extends Model<User> {
allowNull: false,
})
gender: string;
@Column({
type: DataType.STRING,
allowNull: true,
})
refreshToken: string;
}
export enum Gender {
Male = 'male',

@ -17,9 +17,14 @@ export class UsersController {
}
//login as user
@Post("login")
async login(@Body() loginUserDto: LoginUserDto): Promise<{ token }> {
async login(@Body() loginUserDto: LoginUserDto): Promise<{ accessToken; refreshToken }> {
return this.usersService.login(loginUserDto);
}
//get access token
@Post("new-token")
async newAccessToken(@Body("refreshToken") refreshToken: string) {
return this.usersService.newAccessToken(refreshToken);
}
//retrieve a user information
@UseGuards(JwtAuthGuard)
@ -41,6 +46,7 @@ export class UsersController {
async findAll(): Promise<User[]> {
return this.usersService.findAll();
}
// get a specific user info by admin
@UseGuards(RoleGuard)
@Get("users/:id")
async findSpecificUserInfoByUser(@Param("id") id): Promise<User> {

@ -36,7 +36,7 @@ export class UsersService {
}
}
// Login method
async login(loginUserDto: LoginUserDto): Promise<{ token: string }> {
async login(loginUserDto: LoginUserDto): Promise<{ accessToken: string; refreshToken: string }> {
try {
const user = await this.userModel.findOne({
where: { email: loginUserDto.email },
@ -45,18 +45,34 @@ export class UsersService {
if (!user) {
throw new UnauthorizedException("Invalid email or password.");
}
const passwordMatch = await bcrypt.compare(loginUserDto.password, user.password);
if (!passwordMatch) {
throw new UnauthorizedException("Invalid email or password.");
}
const token = this.jwtService.sign(
const accessToken = this.jwtService.sign(
{ id: user.id, role: user.role },
{
secret: this.configService.get<string>("JWT_SECRET"),
expiresIn: this.configService.get<string | number>("JWT_EXPIRES") || "1h",
},
);
return { token };
const refreshToken = this.jwtService.sign(
{ id: user.id },
{
secret: this.configService.get<string>("JWT_REFRESH_SECRET"),
expiresIn: this.configService.get<string | number>("JWT_REFRESH_EXPIRES") || "7d",
},
);
await this.userModel.update(
{ refreshToken }, //
{ where: { id: user.id } },
);
return { accessToken: accessToken, refreshToken: refreshToken };
} catch (error) {
if (error instanceof HttpException) {
throw error;
@ -64,6 +80,36 @@ export class UsersService {
throw new HttpException("An unexpected error occurred. Please try again later.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// getting access token
async newAccessToken(refreshToken: string) {
if (!refreshToken) {
throw new HttpException({ message: "Refresh token is required." }, HttpStatus.BAD_REQUEST);
}
let decoded;
try {
decoded = this.jwtService.verify(refreshToken, { secret: process.env.JWT_REFRESH_SECRET });
} catch (error) {
throw new HttpException({ message: "Invalid or expired token." }, HttpStatus.UNAUTHORIZED);
}
const user = await this.userModel.findOne({
where: { id: decoded.id },
});
if (!user) {
throw new HttpException({ message: "User not found." }, HttpStatus.NOT_FOUND);
}
const accessToken = this.jwtService.sign(
{ id: user.id, role: user.role },
{
secret: this.configService.get<string>("JWT_SECRET"),
expiresIn: this.configService.get<string | number>("JWT_EXPIRES") || "1h",
},
);
return { accessToken };
}
//get information user method
async getProfile(userId: number): Promise<User> {
try {
@ -84,7 +130,7 @@ export class UsersService {
try {
let user = await this.userModel.findOne({ where: { id: userId } });
if (!user) {
throw new NotFoundException('User not found.');
throw new NotFoundException("User not found.");
}
if (updateUserDto.password) {
updateUserDto.password = await bcrypt.hash(updateUserDto.password, 10);
@ -92,14 +138,11 @@ export class UsersService {
await user.update(updateUserDto);
user = await this.userModel.findOne({
where: { id: userId },
attributes: { exclude: ['password'] },
attributes: { exclude: ["password"] },
});
return { message: 'User account updated successfully.', user };
return { message: "User account updated successfully.", user };
} catch (error) {
throw new HttpException(
'An unexpected error occurred. Please try again later.',
HttpStatus.INTERNAL_SERVER_ERROR,
);
throw new HttpException("An unexpected error occurred. Please try again later.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
//get users list
@ -107,10 +150,7 @@ export class UsersService {
try {
return await this.userModel.findAll();
} catch (error) {
throw new HttpException(
'An unexpected error occurred while fetching users.',
HttpStatus.INTERNAL_SERVER_ERROR,
);
throw new HttpException("An unexpected error occurred while fetching users.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
//get users list
@ -118,14 +158,11 @@ export class UsersService {
try {
const user = await this.userModel.findByPk(userId);
if (!user) {
throw new HttpException('User not found.', HttpStatus.NOT_FOUND);
throw new HttpException("User not found.", HttpStatus.NOT_FOUND);
}
return user;
} catch (error) {
throw new HttpException(
'An unexpected error occurred while fetching user information.',
HttpStatus.INTERNAL_SERVER_ERROR,
);
throw new HttpException("An unexpected error occurred while fetching user information.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

Loading…
Cancel
Save