-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDiscordStrategy.mjs
More file actions
85 lines (75 loc) · 2.19 KB
/
DiscordStrategy.mjs
File metadata and controls
85 lines (75 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//DiscordStrategy.mjs
import 'dotenv/config';
import passport from 'passport';
import { Strategy as DiscordStrategy } from 'passport-discord';
import prisma from './database/Prisma.mjs';
passport.serializeUser((user, done) => {
done(null, { id: user.User_discord_id, roles: user.User_roles })
});
passport.deserializeUser(async ({ id, role }, done) => {
const user = await prisma.users.findFirst({
where: {
User_discord_id: id,
}
});
if (user) done(null, user)
else done(new Error("User not found"))
});
passport.use(new DiscordStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: process.env.CLIENT_REDIRECT,
scope: ['identify', 'guilds']
}, async (accessToken, refreshToken, profile, done) => {
//console.log(profile)
try {
const existingUser = await prisma.users.findFirst({
where: {
User_discord_id: profile.id,
},
});
// if user banned
if (existingUser && existingUser.User_is_banned) {
return done(new Error("User is banned"));
}
// if user not in guild
let inGuild = false;
profile.guilds.forEach(element => {
if (element.id === process.env.DISCORD_GUILD_ID) {
inGuild = true;
return;
}
});
if (!inGuild) {
return done(new Error("User is not in the guild. Join https://discord.gg/FTkj9xUvHh and try again."));
}
if (existingUser) {
const updatedUser = await prisma.users.update({
where: {
User_discord_id: profile.id
},
data: {
User_discord_access_token: accessToken,
User_discord_refresh_token: refreshToken,
}
});
//console.log(updatedUser)
return done(null, updatedUser);
} else {
const newUser = await prisma.users.create({
data: {
User_displayname: profile.username,
User_discord_id: profile.id,
User_discord_username: profile.username,
User_discord_access_token: accessToken,
User_discord_refresh_token: refreshToken,
},
});
//console.log(newUser)
return done(null, newUser);
}
} catch (err) {
console.error(err);
done(err);
}
}));