Skip to content

Commit

Permalink
Update permissions
Browse files Browse the repository at this point in the history
  • Loading branch information
Smaug6739 committed Jun 3, 2021
1 parent 4755041 commit dfbefbf
Show file tree
Hide file tree
Showing 9 changed files with 275 additions and 0 deletions.
22 changes: 22 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
s
</body>

</html>

<script>
async function test() {
fetch('http://localhost:3000/test')
}
test()
</script>
15 changes: 15 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,25 @@ export class App {
console.log(`Route chargée : /api/v${getFileName.infos.version}/${getFileName.infos.route}`);
}
})
this.app.set('trust proxy', true)
this.app.get('/test', (req: any, res: any) => {
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
console.log('ip : ' + ip); // ip address of the user
res.end()
})
}
private handleMiddlewares(): void {
this.app.use(express.urlencoded({ extended: true }));
this.app.use(express.json());
this.app.use(function (req: any, res: any, next: Function) {
const origin = req.headers.origin;
res.setHeader('Access-Control-Allow-Origin', origin)

res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
res.setHeader('Access-Control-Allow-Credentials', 'true')
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
next()
})
}
public start(): void {
this.handleMiddlewares();
Expand Down
17 changes: 17 additions & 0 deletions src/assets/classes/v2/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import db from '../../../models/db';
import { IObject } from '../../../types';
const Authentication = class {
private config;
constructor(server: any) {
this.config = server.config
}
logUser(userId: string, infos: IObject) {
return new Promise((resolve, reject) => {
if (!userId) return reject(new Error('Missing user id'));
if (!infos || infos && infos.username) return reject(new Error('Missing username.'))
if (!infos || infos && infos.password) return reject(new Error('Missing password.'))
db.query('')
})
}

}
21 changes: 21 additions & 0 deletions src/routes/v2/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Router } from 'express';
import * as MemberCtrl from '../../controllers/members';
import { Iroute } from '../../types';
import auth from '../../middlewares/auth';
const MemberRouter: Router = Router();

MemberRouter.post('/', MemberCtrl.createMember);
MemberRouter.post('/auth', MemberCtrl.auth);

MemberRouter.get('/all/:page', auth, MemberCtrl.getMembers);
MemberRouter.get('/:userId', auth, MemberCtrl.getMember);

MemberRouter.put('/:userId', auth, MemberCtrl.updateMember);

MemberRouter.delete('/:userId', auth, MemberCtrl.deleteMember)

export const infos: Iroute = {
route: "auth",
version: 2,
router: MemberRouter
};
21 changes: 21 additions & 0 deletions src/routes/v2/members.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Router } from 'express';
import * as MemberCtrl from '../../controllers/members';
import { Iroute } from '../../types';
import auth from '../../middlewares/auth';
const MemberRouter: Router = Router();

MemberRouter.post('/', MemberCtrl.createMember);
MemberRouter.post('/auth', MemberCtrl.auth);

MemberRouter.get('/all/:page', auth, MemberCtrl.getMembers);
MemberRouter.get('/:userId', auth, MemberCtrl.getMember);

MemberRouter.put('/:userId', auth, MemberCtrl.updateMember);

MemberRouter.delete('/:userId', auth, MemberCtrl.deleteMember)

export const infos: Iroute = {
route: "members",
version: 2,
router: MemberRouter
};
80 changes: 80 additions & 0 deletions src/utils/Permissions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
class Permissions {
private bits: number; // User bits permissions
public FLAGS = [
{ value: 1 << 1, name: 'ADMINISTRATOR' },
{ value: 1 << 2, name: 'VIEW_ALL_MEMBERS' },
{ value: 1 << 3, name: 'UPDATE_MEMBERS' },
{ value: 1 << 4, name: 'DELETE_MEMBERS' },
{ value: 1 << 5, name: 'BAN_MEMBERS' },
]
constructor(bits: number) {
this.bits = bits;
}
get ALL() {
let bit = 0;
for (let flag of this.FLAGS) {
bit += flag.value
}
return bit
}
get permissionCalc() {
return this.bits;
}
public toArray() {

let bits = this.bits;
const flags = [...this.FLAGS].reverse()

const userPermissions: any[] = []
for (let permission of flags) {

const rest = bits % permission.value;
if (rest == 0 && bits != 0) {
userPermissions.push(permission.name);
break;
}
if (rest < bits) {
userPermissions.push(permission.name);
bits = rest
}
}
return userPermissions
}
public hasPermissions(permission: any): boolean {
if (Array.isArray(permission)) return permission.every(p => this.hasPermissions(p))
const permissionsArray = this.toArray();
if (permissionsArray.includes('ADMINISTRATOR')) return true;
if (typeof permission === 'string') {


if (permissionsArray.includes(permission)) return true;
else return false;
}
if (typeof permission === 'number') {
let hasPermissions = false;
this.FLAGS.map(p => {
if (p.value === permission) hasPermissions = true;
})
return hasPermissions;
}
return false
}
public calculate(permissions: string | string[]) {
if (typeof permissions === 'string') {
const permission = this.FLAGS.find(f => f.name === permissions.toUpperCase());
return permission ? permission : undefined;
}
if (Array.isArray(permissions)) {
let some = 0;
permissions.map(p => {
const permission = this.FLAGS.find(perm => perm.name === p.toUpperCase())
if (permission) some += permission.value;
})
}
}
}

const test = new Permissions(2)

console.log(test.toArray());
console.log(test.hasPermissions([16, 'DELETE_MEMBERSs']));
Empty file added tests/permissions.js
Empty file.
59 changes: 59 additions & 0 deletions tests/t.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const filter = (reaction, user) => reaction.emoji.name === settings.ReactionClose && !user.bot;


collector.on("collect", collected => {
var bvn = new MessageEmbed()
.setDescription(`Votre ticket a bien été cloturée.`)
.setFooter(`Ticket bot`)
.setColor("RANDOM")
.setTitle(`Ticket cloturée.`)
// channel_ticket.messages.fetch(bvn)

channel_ticket.send(bvn)
channel_ticket.delete({ timeout: 15000 });


// channel_ticket.setTimeout(() => {
// channel_ticket.delete()
// }, 15000);
});


const filter = (reaction, user) => reaction.emoji.name === "📜" && user.id == '531137738108305409' && !user.bot;


collector.on("collect", collected => {
if (!collector.member.hasPermission("BAN_MEMBERS")) return message.channel.send(` :x: Tu n'as pas la permission`).then(msg => msg.delete({ timeout: 5000 }));

const channel = message.mentions.channels.first() || message.guild.channels.cache.get(args[0]) || message.channel;

if (message.member.hasPermission('ADMINISTRATOR') || channel.name === `ticket-${message.author.id}`) {


channel.messages.fetch().then(async (messages) => {
const output = messages.array().reverse().map(m => `${new Date(m.createdAt).toLocaleString('fr-fr')} - ${m.author.tag}: ${m.attachments.size > 0 ? m.attachments.first().proxyURL : m.content}`).join('\n');

let response;
try {
response = await sourcebin.create([
{
name: ' ',
content: output,
languageId: 'text',
},
], {
title: `Chat transcript for ${channel.name}`,
description: ' ',
});
}
catch (e) {
return message.channel.send('An error occurred, please try again!');
}

const embed = new MessageEmbed()
.setDescription(`[\`📄 View\`](${response.url})`)
.setColor('GREEN');
channel_ticket.send('the transcript is complete. Please click the link below to view the transcript', embed);
});
}
})
40 changes: 40 additions & 0 deletions tests/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const FLAGS = {
CREATE_INSTANT_INVITE: 1 << 0,
KICK_MEMBERS: 1 << 1,
BAN_MEMBERS: 1 << 2,
ADMINISTRATOR: 1 << 3,
MANAGE_CHANNELS: 1 << 4,
MANAGE_GUILD: 1 << 5,
ADD_REACTIONS: 1 << 6,
VIEW_AUDIT_LOG: 1 << 7,
PRIORITY_SPEAKER: 1 << 8,
STREAM: 1 << 9,
VIEW_CHANNEL: 1 << 10,
SEND_MESSAGES: 1 << 11,
SEND_TTS_MESSAGES: 1 << 12,
MANAGE_MESSAGES: 1 << 13,
EMBED_LINKS: 1 << 14,
ATTACH_FILES: 1 << 15,
READ_MESSAGE_HISTORY: 1 << 16,
MENTION_EVERYONE: 1 << 17,
USE_EXTERNAL_EMOJIS: 1 << 18,
VIEW_GUILD_INSIGHTS: 1 << 19,
CONNECT: 1 << 20,
SPEAK: 1 << 21,
MUTE_MEMBERS: 1 << 22,
DEAFEN_MEMBERS: 1 << 23,
MOVE_MEMBERS: 1 << 24,
USE_VAD: 1 << 25,
CHANGE_NICKNAME: 1 << 26,
MANAGE_NICKNAMES: 1 << 27,
MANAGE_ROLES: 1 << 28,
MANAGE_WEBHOOKS: 1 << 29,
MANAGE_EMOJIS: 1 << 30,
};
let permission = 16;
let i = 0
const permissions = Object.keys(FLAGS)
const has = permissions.filter(bit => {
return FLAGS[bit] === permission
})
console.log(has);

0 comments on commit dfbefbf

Please sign in to comment.