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

Whitelist codes #54

Open
wants to merge 24 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
f3f2990
Merge pull request #48 from fileverse/feat/whitelist-codes
vijaykrishnavanshi May 20, 2024
8ede01b
ONLY_FILES removed from whitelist codes
anubhavitis May 28, 2024
efb5c4d
Merge pull request #51 from fileverse/feat/whitelist-codes
anubhavitis May 28, 2024
16dc573
ARWEAVE removed from whitelist codes
anubhavitis May 28, 2024
6c6546d
Merge pull request #52 from fileverse/feat/whitelist-codes
anubhavitis May 28, 2024
ac953ac
added endpoint to handle whitelist codes directly
anubhavitis Jun 7, 2024
a9162fd
added endpoint to handle whitelist address directly
anubhavitis Jun 7, 2024
e52651a
Merge branch 'whitelist_addr' of github.com:fileverse/fileverse-gate …
anubhavitis Jun 7, 2024
93c1465
added seggregated /codes:
anubhavitis Jun 7, 2024
9e4fab0
added api key to auth the request, and added new endpoint to check th…
anubhavitis Jun 7, 2024
0b34218
added author to track the ownership of whitelisting an address
anubhavitis Jun 7, 2024
c7ebd59
Merge branch 'whitelist_addr' of github.com:fileverse/fileverse-gate …
anubhavitis Jun 7, 2024
0a1f7df
finalised /codes endpoint
anubhavitis Jun 7, 2024
3af01b7
fixed issues while testing
anubhavitis Jun 7, 2024
76b4966
added functionality to update the count when code is used
anubhavitis Jun 7, 2024
0171add
removed unwanted imports
anubhavitis Jun 8, 2024
1e09e43
Added old code back for whitelist
vijaykrishnavanshi Jun 8, 2024
ba6d0ae
Merge branch 'main' of github.com:fileverse/fileverse-gate into white…
anubhavitis Jun 17, 2024
00341ce
renamed author => addedBy
anubhavitis Jul 11, 2024
f65a020
renamed author => addedBy
anubhavitis Jul 11, 2024
9cee856
renamed fuction and IsWhitelisted endpoint response
anubhavitis Jul 11, 2024
17b6334
pr comments resolved
anubhavitis Jul 11, 2024
d52127d
Merge branch 'whitelist_addr' of github.com:fileverse/fileverse-gate …
anubhavitis Jul 11, 2024
5c84c50
tested code in local
anubhavitis Jul 11, 2024
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
1 change: 1 addition & 0 deletions config/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ S3_KMS_KEY=
S3_REGION=
S3_SECRET_ACCESS_KEY=
SERVICE_DID=
WHITELIST_ADMIN_API_KEY=
8 changes: 2 additions & 6 deletions src/domain/account/whitelist/codes.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,13 @@
"description": "ETHDENVER Campaign"
},
{
"code": "ARWEAVE",
"description": "Areweave Developers"
"code": "ONLY_FILES",
"description": "Only Files Campaign"
},
{
"code": "FILEVERSE_SUMMER",
"description": "Limited Activity"
},
{
"code": "ONLY_FILES",
"description": "Allowlisted Portals"
},
{
"code": "FARCASTER1",
"description": "BountyCaster - 7 Days Activity"
Expand Down
19 changes: 14 additions & 5 deletions src/domain/account/whitelist/hasReferralCode.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
const codes = require("./codes.json");
const WhitelistCodes = require("../../whitelistCodes")

async function hasReferralCode({ code }) {
if (!code) {
return false;
}
const found = codes.find(
(elem) => elem.code.toLowerCase() === code.toLowerCase()
);
return !!found;
const resp = await WhitelistCodes.isEnalbed({ code });

if (resp == false) {
return false;
}

try {
_ = await WhitelistCodes.updateCount({ code });
} catch (e) {
console.error("failed to update the count of code", code, "due to ", e);
}
return true;

}

module.exports = hasReferralCode;
12 changes: 12 additions & 0 deletions src/domain/whitelist/create.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const { Whitelist } = require('../../infra/database/models')

async function create({ addressList, tag, addedBy }) {
tag = tag || 'personal-invite'
const bulkData = addressList.map((addr) => {
return { invokerAddress: addr, tag: tag, addedBy: addedBy }
})

await Whitelist.insertMany(bulkData)
}

module.exports = create;
8 changes: 8 additions & 0 deletions src/domain/whitelist/find.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const { Whitelist } = require('../../infra/database/models')

async function find({ address }) {
const result = await Whitelist.findOne({ invokerAddress: address });
return result;
}

module.exports = find;
4 changes: 4 additions & 0 deletions src/domain/whitelist/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const create = require('./create');
const find = require('./find');

module.exports = { create, find };
12 changes: 12 additions & 0 deletions src/domain/whitelistCodes/disable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const { WhitelistCodes } = require("../../infra/database/models");

async function disable({ codes }) {
const updatedWhitelistCodesData = await WhitelistCodes.findOneAndUpdate(
{ code: { $in: codes } },
{ status: 'inactive' },
{ new: true }
);
return updatedWhitelistCodesData;
}

module.exports = disable;
32 changes: 32 additions & 0 deletions src/domain/whitelistCodes/get.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const { WhitelistCodes } = require("../../infra/database/models");

async function getByCode({ code }) {
return await WhitelistCodes.findOne({ code });
}

async function getAllByStatus({ status }) {

const whitelistCodes = WhitelistCodes.find({ status });
if (status == 'active') {
whitelistCodes.find({
$and: [
{
$or: [
{ expiry: null },
{ expiry: { $lt: Date.now() } }
]
},
{
$or: [
{ allowedUses: null },
{ $expr: { $gt: ['$allowedUses', '$used'] } }
]
}
]
})
}

return await whitelistCodes;
}

module.exports = { getAllByStatus, getByCode };
7 changes: 7 additions & 0 deletions src/domain/whitelistCodes/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const isEnalbed = require("./isEnabled");
const add = require("./newCodes");
const disable = require("./disable");
const { getAllByStatus, getByCode } = require("./get");
const updateCount = require("./updateCount");

module.exports = { isEnalbed, add, disable, updateCount, getAllByStatus, getByCode };
17 changes: 17 additions & 0 deletions src/domain/whitelistCodes/isEnabled.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const { WhitelistCodes } = require("../../infra/database/models");

async function isEnalbed({ code }) {
const whitelistCode = await WhitelistCodes.findOne({ code });

if (whitelistCode.status != 'active') {
return false;
} else if (whitelistCode.expiry && whitelistCode.expiry < new Date()) {
return false;
} else if (whitelistCode.allowedUses && whitelistCode.allowedUses <= whitelistCode.used) {
return false;
} else {
return true;
}
}

module.exports = isEnalbed;
21 changes: 21 additions & 0 deletions src/domain/whitelistCodes/newCodes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const { WhitelistCodes } = require("../../infra/database/models");

async function add({ code, description, expiry, status, allowedUses, timeStamp }) {
const isExistingCode = await WhitelistCodes.findOne({ code });
if (isExistingCode) {
throw new Error('Code already exists');
}

const createdWhitelistCodesData = await WhitelistCodes.create({
code,
description,
expiry: expiry ? new Date(expiry) : null,
status,
allowedUses: allowedUses || null,
timeStamp,
});

return createdWhitelistCodesData;
}

module.exports = add;
13 changes: 13 additions & 0 deletions src/domain/whitelistCodes/updateCount.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const { WhitelistCodes } = require("../../infra/database/models");

async function updateCount({ code }) {
const whitelistCode = await WhitelistCodes.findOneAndUpdate(
{ code },
{ $inc: { used: 1 } },
{ new: true }
);

return whitelistCode;
}

module.exports = updateCount;
1 change: 1 addition & 0 deletions src/infra/database/models/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const _models = {
Gate: require("./gate").model,
Whitelist: require("./whitelist").model,
Heart: require("./heart").model,
WhitelistCodes: require("./whitelistCodes").model,
};

module.exports = _models;
2 changes: 2 additions & 0 deletions src/infra/database/models/whitelist.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ _whitelist.schema = new Schema({
required: true,
default: Date.now
},
addedBy: { type: String },
});

_whitelist.schema.pre('save', function (next) {
Expand All @@ -28,6 +29,7 @@ _whitelist.schema.methods.safeObject = function () {
'invokerAddress',
'tag',
'timeStamp',
'addedBy'
];
const newSafeObject = {};
safeFields.forEach((elem) => {
Expand Down
67 changes: 67 additions & 0 deletions src/infra/database/models/whitelistCodes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const mongoose = require('mongoose');
const { Schema } = mongoose;

const _whitelist_codes = {};



_whitelist_codes.schema = new Schema({
code: {
type: String,
required: true
},
description: {
type: String,
required: true
},
timeStamp: {
type: Date,
required: true,
default: Date.now
},
status: {
type: String,
required: true,
enum: ['active', 'inactive', 'expired'], // Optional: to restrict the values for status
default: 'active'
},
expiry: {
type: Date,
required: false
},
allowedUses: {
type: Number,
required: false,
},
used: {
type: Number,
required: true,
default: 0
}
});

_whitelist_codes.schema.pre('save', function (next) {
this.timeStamp = Date.now();
next();
});

_whitelist_codes.schema.methods.safeObject = function () {
const safeFields = [
'_id',
'code',
'description',
'expiry',
'status',
'timeStamp',
];
const newSafeObject = {};
safeFields.forEach((elem) => {
// eslint-disable-next-line security/detect-object-injection
newSafeObject[elem] = this[elem];
});
return newSafeObject;
};

_whitelist_codes.model = mongoose.model('whitelist_codes', _whitelist_codes.schema);

module.exports = _whitelist_codes;
2 changes: 2 additions & 0 deletions src/interface/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ const router = express.Router();
const gate = require('./gate');
const account = require('./account');
const contract = require('./contract');
const whitelist = require('./whitelist');

router.use('/gate', gate);
router.use('/account', account);
router.use('/contract', contract);
router.use('/whitelist', whitelist);

module.exports = router;
1 change: 1 addition & 0 deletions src/interface/middleware/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ module.exports = {
canRegisterMember: require('./canRegisterMember'),
canCheckWhitelist: require('./canCheckWhitelist'),
errorHandler: require('./errorHandler'),
whitelistAdmin: require('./whitelistAdmin'),
validator: require('./validator'),
};
19 changes: 19 additions & 0 deletions src/interface/middleware/whitelistAdmin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const ErrorHandler = require('../../infra/errorHandler');
const config = require('../../../config');

const whitelistAdminApiKey = config.WHITELIST_ADMIN_API_KEY;

async function whitelistAdmin(req, res, next) {
const xApiKey = req.headers['x-api-key'];
if (!xApiKey || !whitelistAdminApiKey || xApiKey !== whitelistAdminApiKey) {
return ErrorHandler.throwError({
code: 401,
message: 'Unauthorized',
req,
});
}

next();
}

module.exports = whitelistAdmin;
27 changes: 27 additions & 0 deletions src/interface/whitelist/address/address.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const Whitelist = require('../../../domain/whitelist');
const { validator } = require("../../middleware");
const { Joi, validate } = validator;

const whiteListAddressValidation = {
body: Joi.object({
addressList: Joi.array().items(
Joi.string().required(),
).required(),
tag: Joi.string().optional(),
addedBy: Joi.string().required(),
}),
};


async function whitelistAddress(req, res) {
const { addressList, tag, addedBy } = req.body;
try {
await Whitelist.create({ addressList, tag, addedBy });
res.json({ success: true, error: null });
}
catch (error) {
return res.status(400).json({ success: false, error: error.message });
}
}

module.exports = [validate(whiteListAddressValidation), whitelistAddress];
17 changes: 17 additions & 0 deletions src/interface/whitelist/address/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const express = require('express');

const router = express.Router();

const {
asyncHandler,
asyncHandlerArray,
} = require('../../../infra/asyncHandler');

const whitelistAddress = require('./address');
const isWhitelistedAddress = require('./isWhitelistedAddress');
const { whitelistAdmin } = require('../../middleware');

router.post('/address', asyncHandler(whitelistAdmin), asyncHandlerArray(whitelistAddress));
router.get('/address/:address', asyncHandler(isWhitelistedAddress));

module.exports = router;
Loading