Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

User Device Token #2535

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
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
67 changes: 66 additions & 1 deletion server/api/controllers/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -1154,6 +1154,69 @@ const userDelete = (req, res) => {
};


const createUserDeviceToken = (req, res) => {
loggerUser.verbose(
req.uuid,
'controllers/user/createUserDeviceToken auth',
req.auth.sub
);

const { id: userId } = req.auth.sub;
const { token, device } = req.swagger.params.data.value;

loggerUser.verbose(
req.uuid,
'controllers/user/createUserDeviceToken data',
token,
device
);

toolsLib.user.createUserDeviceToken(userId, token, device)
.then(() => {
return res.json({ message: 'Success' });
})
.catch((err) => {
loggerUser.error(
req.uuid,
'controllers/user/createUserDeviceToken',
err.message,
err.stack
);
return res.status(err.statusCode || 400).json({ message: errorMessageConverter(err) });
});
}

const getUserDeviceToken = (req, res) => {
loggerUser.verbose(
req.uuid,
'controllers/user/getUserDeviceToken auth',
req.auth.sub
);

const { id: userId } = req.auth.sub;
const { device } = req.swagger.params;

loggerUser.verbose(
req.uuid,
'controllers/user/getUserDeviceToken data',
device
);

toolsLib.user.getUserDeviceToken(userId, device.value)
.then((data) => {
return res.json(data);
})
.catch((err) => {
loggerUser.error(
req.uuid,
'controllers/user/getUserDeviceToken',
err.message,
err.stack
);
return res.status(err.statusCode || 400).json({ message: errorMessageConverter(err) });
});
}

module.exports = {
signUpUser,
getVerifyUser,
Expand Down Expand Up @@ -1183,5 +1246,7 @@ module.exports = {
revokeUserSession,
getUserSessions,
userLogout,
userDelete
userDelete,
createUserDeviceToken,
getUserDeviceToken
};
73 changes: 73 additions & 0 deletions server/api/swagger/user.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -914,6 +914,79 @@ paths:
- bearer
x-security-scopes:
- user
/user/device-token:
x-swagger-router-controller: user
post:
operationId: createUserDeviceToken
description: Create device token for user
tags:
- User
parameters:
- name: data
in: body
required: true
schema:
type: object
required:
- token
- device
properties:
token:
type: string
maxLength: 256
device:
type: string
maxLength: 256
responses:
200:
description: Success
schema:
$ref: "#/definitions/ObjectResponse"
default:
description: Error
schema:
$ref: "#/definitions/MessageResponse"
security:
- Token: []
x-security-types:
- bearer
- hmac
x-security-scopes:
- user
get:
operationId: getUserDeviceToken
description: get device token of authenticated user
tags:
- User
parameters:
- in: query
name: device
description: device
required: true
type: string
maxLength: 256
responses:
200:
description: Success
schema:
$ref: "#/definitions/ObjectResponse"
202:
description: CSV
schema:
type: string
default:
description: Error
schema:
$ref: "#/definitions/MessageResponse"
security:
- Token: []
x-security-types:
- bearer
- hmac
x-security-scopes:
- user
x-token-permissions:
- can_read
/user/trades:
x-swagger-router-controller: trade
get:
Expand Down
50 changes: 50 additions & 0 deletions server/db/migrations/20231220100478-create-device-token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
'use strict';

module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('DeviceTokens', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
user_id: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
allowNull: false,
references: {
model: 'Users',
key: 'id'
}
},
token: {
type: Sequelize.STRING,
allowNull: false,
},
device: {
type: Sequelize.STRING,
allowNull: false,
},
status: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: true
},
created_at: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.literal('NOW()'),
},
updated_at: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.literal('NOW()'),
},
});
},

down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('DeviceTokens');
},
};
53 changes: 53 additions & 0 deletions server/db/models/deviceToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'use strict';

module.exports = function (sequelize, DataTypes) {

const DeviceToken = sequelize.define(
'DeviceToken',
{
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
user_id: {
type: DataTypes.INTEGER,
onDelete: 'CASCADE',
allowNull: false,
references: {
model: 'Users',
key: 'id'
}
},
token: {
type: DataTypes.STRING,
allowNull: false,
},
device: {
type: DataTypes.STRING,
allowNull: false,
},
status: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
},
},
{
timestamps: true,
underscored: true,
tableName: 'DeviceTokens'
}
);

DeviceToken.associate = (models) => {
DeviceToken.belongsTo(models.User, {
onDelete: 'CASCADE',
foreignKey: 'user_id',
targetKey: 'id'
});
};

return DeviceToken;
};
2 changes: 2 additions & 0 deletions server/db/models/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ model = require(path.join(__dirname, './staker'))(sequelize, Sequelize.DataTypes
db[model.name] = model;
model = require(path.join(__dirname, './transactionLimit'))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
model = require(path.join(__dirname, './deviceToken'))(sequelize, Sequelize.DataTypes);
db[model.name] = model;

Object.keys(db).forEach(function (modelName) {
if ('associate' in db[modelName]) {
Expand Down
4 changes: 3 additions & 1 deletion server/messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -260,4 +260,6 @@ exports.CANNOT_CHANGE_ADMIN_EMAIL = 'Cannot change admin email';
exports.EMAIL_IS_SAME = 'New email cannot be same as the existing one';
exports.EMAIL_EXISTS = 'This email already exists';
exports.CANNOT_CHANGE_DELETED_EMAIL = 'Cannot change deleted email';
exports.FAILED_GET_QUOTE = 'Failed to get the quote';
exports.FAILED_GET_QUOTE = 'Failed to get the quote';
exports.DEVICE_TOKEN_EXITS = 'Active token already exits';
exports.DEVICE_TOKEN_NOT_FOUND = 'Active token not found';
73 changes: 71 additions & 2 deletions server/utils/hollaex-tools-lib/tools/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ const {
EMAIL_IS_SAME,
EMAIL_EXISTS,
CANNOT_CHANGE_DELETED_EMAIL,
SERVICE_NOT_SUPPORTED
SERVICE_NOT_SUPPORTED,
DEVICE_TOKEN_EXITS,
DEVICE_TOKEN_NOT_FOUND
} = require(`${SERVER_PATH}/messages`);
const { publisher, client } = require('./database/redis');
const {
Expand Down Expand Up @@ -2342,6 +2344,71 @@ const changeKitUserEmail = async (userId, newEmail, auditInfo) => {
return updatedUser;
};

const createUserDeviceToken = async (userId, token, device) => {
const user = await dbQuery.findOne('user', {
where: {
id: userId
},
attributes: [
'id',
'email'
]
});

if (!user) {
throw new Error(USER_NOT_FOUND);
}

const userToken = await dbQuery.findOne('deviceToken', {
where: {
token,
status: true
},
});

if (userToken) {
throw new Error(DEVICE_TOKEN_EXITS);
}

return getModel('deviceToken').create({
user_id: userId,
token,
device,
})

}

const getUserDeviceToken = async (userId, device) => {

const user = await dbQuery.findOne('user', {
where: {
id: userId
},
attributes: [
'id',
'email'
]
});

if (!user) {
throw new Error(USER_NOT_FOUND);
}

const token = await dbQuery.findOne('deviceToken', {
where: {
user_id: userId,
device,
status: true
},
});


if (!token) {
throw new Error(DEVICE_TOKEN_NOT_FOUND);
}
return { token };
}

module.exports = {
loginUser,
getUserTier,
Expand Down Expand Up @@ -2402,5 +2469,7 @@ module.exports = {
changeKitUserEmail,
storeVerificationCode,
signUpUser,
verifyUser
verifyUser,
createUserDeviceToken,
getUserDeviceToken
};