Skip to content

Commit

Permalink
Merge pull request #103 from matthe815/feature/discord-login
Browse files Browse the repository at this point in the history
feat: Password resetting by Discord integration
  • Loading branch information
sekaiwish authored Jan 2, 2024
2 parents 4f5eeb1 + 63388aa commit d6322e2
Show file tree
Hide file tree
Showing 9 changed files with 164 additions and 22 deletions.
11 changes: 10 additions & 1 deletion config.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,11 @@
"Discord": {
"Enabled": false,
"BotToken": "",
"RealtimeChannelID": ""
"RealTimeChannel": {
"Enabled": false,
"MaxMessageLength": 183,
"RealTimeChannelID": ""
}
},
"Commands": [
{
Expand Down Expand Up @@ -127,6 +131,11 @@
"Enabled": true,
"Description": "Link a PlayStation Network ID to your account",
"Prefix": "psn"
}, {
"Name": "Discord",
"Enabled": true,
"Description": "Generate a token to link your Discord account",
"Prefix": "discord"
}
],
"Courses": [
Expand Down
12 changes: 9 additions & 3 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,15 @@ type GameplayOptions struct {

// Discord holds the discord integration config.
type Discord struct {
Enabled bool
BotToken string
RealtimeChannelID string
Enabled bool
BotToken string
RelayChannel DiscordRelay
}

type DiscordRelay struct {
Enabled bool
MaxMessageLength int
RelayChannelID string
}

// Command is a channelserver chat command
Expand Down
6 changes: 6 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,12 @@ func main() {
}

discordBot = bot

_, err = discordBot.Session.ApplicationCommandBulkOverwrite(discordBot.Session.State.User.ID, "", discordbot.Commands)
if err != nil {
preventClose(fmt.Sprintf("Discord: Failed to start, %s", err.Error()))
}

logger.Info("Discord: Started successfully")
} else {
logger.Info("Discord: Disabled")
Expand Down
6 changes: 6 additions & 0 deletions patch-schema/16-discord-password-resets.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
BEGIN;

ALTER TABLE IF EXISTS public.users ADD COLUMN discord_token text;
ALTER TABLE IF EXISTS public.users ADD COLUMN discord_id text;

END;
15 changes: 15 additions & 0 deletions server/channelserver/handlers_cast_binary.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package channelserver

import (
"crypto/rand"
"encoding/hex"
"erupe-ce/common/byteframe"
"erupe-ce/common/mhfcourse"
Expand Down Expand Up @@ -322,6 +323,20 @@ func parseChatCommand(s *Session, command string) {
} else {
sendDisabledCommandMessage(s, commands["Teleport"])
}
case commands["Discord"].Prefix:
if commands["Discord"].Enabled {
var _token string
err := s.server.db.QueryRow(`SELECT discord_token FROM users u WHERE u.id=(SELECT c.user_id FROM characters c WHERE c.id=$1)`, s.charID).Scan(&_token)
if err != nil {
randToken := make([]byte, 4)
rand.Read(randToken)
_token = fmt.Sprintf("%x-%x", randToken[:2], randToken[2:])
s.server.db.Exec(`UPDATE users u SET discord_token = $1 WHERE u.id=(SELECT c.user_id FROM characters c WHERE c.id=$2)`, _token, s.charID)
}
sendServerChatMessage(s, fmt.Sprintf(s.server.dict["commandDiscordSuccess"], _token))
} else {
sendDisabledCommandMessage(s, commands["Discord"])
}
case commands["Help"].Prefix:
if commands["Help"].Enabled {
for _, command := range commands {
Expand Down
70 changes: 65 additions & 5 deletions server/channelserver/handlers_discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package channelserver
import (
"fmt"
"github.com/bwmarrin/discordgo"
"golang.org/x/crypto/bcrypt"
"sort"
"strings"
"unicode"
Expand Down Expand Up @@ -66,10 +67,56 @@ func getCharacterList(s *Server) string {
return message
}

// onInteraction handles slash commands
func (s *Server) onInteraction(ds *discordgo.Session, i *discordgo.InteractionCreate) {
switch i.Interaction.ApplicationCommandData().Name {
case "link":
var temp string
err := s.db.QueryRow(`UPDATE users SET discord_id = $1 WHERE discord_token = $2 RETURNING discord_id`, i.Member.User.ID, i.ApplicationCommandData().Options[0].StringValue()).Scan(&temp)
if err == nil {
ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Your Erupe account was linked successfully.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
} else {
ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Failed to link Erupe account.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
}
case "password":
password, _ := bcrypt.GenerateFromPassword([]byte(i.ApplicationCommandData().Options[0].StringValue()), 10)
_, err := s.db.Exec(`UPDATE users SET password = $1 WHERE discord_id = $2`, password, i.Member.User.ID)
if err == nil {
ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Your Erupe account password has been updated.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
} else {
ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Failed to update Erupe account password.",
Flags: discordgo.MessageFlagsEphemeral,
},
})
}
}
}

// onDiscordMessage handles receiving messages from discord and forwarding them ingame.
func (s *Server) onDiscordMessage(ds *discordgo.Session, m *discordgo.MessageCreate) {
// Ignore messages from our bot, or ones that are not in the correct channel.
if m.Author.Bot || m.ChannelID != s.erupeConfig.Discord.RealtimeChannelID {
// Ignore messages from bots, or messages that are not in the correct channel.
if m.Author.Bot || m.ChannelID != s.erupeConfig.Discord.RelayChannel.RelayChannelID {
return
}

Expand All @@ -79,11 +126,24 @@ func (s *Server) onDiscordMessage(ds *discordgo.Session, m *discordgo.MessageCre
}
return r
}, m.Author.Username))

for i := 0; i < 8-len(m.Author.Username); i++ {
paddedName += " "
}
message := s.discordBot.NormalizeDiscordMessage(fmt.Sprintf("[D] %s > %s", paddedName, m.Content))
if len(message) > s.erupeConfig.Discord.RelayChannel.MaxMessageLength {
return
}

message := fmt.Sprintf("[D] %s > %s", paddedName, m.Content)
s.BroadcastChatMessage(s.discordBot.NormalizeDiscordMessage(message))
var messages []string
lineLength := 61
for i := 0; i < len(message); i += lineLength {
end := i + lineLength
if end > len(message) {
end = len(message)
}
messages = append(messages, message[i:end])
}
for i := range messages {
s.BroadcastChatMessage(messages[i])
}
}
1 change: 1 addition & 0 deletions server/channelserver/sys_channel_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ func (s *Server) Start() error {
// Start the discord bot for chat integration.
if s.erupeConfig.Discord.Enabled && s.discordBot != nil {
s.discordBot.Session.AddHandler(s.onDiscordMessage)
s.discordBot.Session.AddHandler(s.onInteraction)
}

return nil
Expand Down
4 changes: 4 additions & 0 deletions server/channelserver/sys_language.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ func getLangStrings(s *Server) map[string]string {
strings["commandPSNSuccess"] = "PSN「%s」が連携されています"
strings["commandPSNExists"] = "PSNは既存のユーザに接続されています"

strings["commandDiscordSuccess"] = "あなたのDiscordトークン:%s"

strings["commandRaviNoCommand"] = "ラヴィコマンドが指定されていません"
strings["commandRaviStartSuccess"] = "大討伐を開始します"
strings["commandRaviStartError"] = "大討伐は既に開催されています"
Expand Down Expand Up @@ -78,6 +80,8 @@ func getLangStrings(s *Server) map[string]string {
strings["commandPSNSuccess"] = "Connected PSN ID: %s"
strings["commandPSNExists"] = "PSN ID is connected to another account!"

strings["commandDiscordSuccess"] = "Your Discord token: %s"

strings["commandRaviNoCommand"] = "No Raviente command specified!"
strings["commandRaviStartSuccess"] = "The Great Slaying will begin in a moment"
strings["commandRaviStartError"] = "The Great Slaying has already begun!"
Expand Down
61 changes: 48 additions & 13 deletions server/discordbot/discord_bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,39 @@ import (
"regexp"
)

var Commands = []*discordgo.ApplicationCommand{
{
Name: "link",
Description: "Link your Erupe account to Discord",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "token",
Description: "The token provided by the Discord command in-game",
Required: true,
},
},
},
{
Name: "password",
Description: "Change your Erupe account password",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "password",
Description: "Your new password",
Required: true,
},
},
},
}

type DiscordBot struct {
Session *discordgo.Session
config *_config.Config
logger *zap.Logger
MainGuild *discordgo.Guild
RealtimeChannel *discordgo.Channel
Session *discordgo.Session
config *_config.Config
logger *zap.Logger
MainGuild *discordgo.Guild
RelayChannel *discordgo.Channel
}

type Options struct {
Expand All @@ -28,18 +55,22 @@ func NewDiscordBot(options Options) (discordBot *DiscordBot, err error) {
return nil, err
}

realtimeChannel, err := session.Channel(options.Config.Discord.RealtimeChannelID)
var relayChannel *discordgo.Channel

if options.Config.Discord.RelayChannel.Enabled {
relayChannel, err = session.Channel(options.Config.Discord.RelayChannel.RelayChannelID)
}

if err != nil {
options.Logger.Fatal("Discord failed to create realtimeChannel", zap.Error(err))
options.Logger.Fatal("Discord failed to create relayChannel", zap.Error(err))
return nil, err
}

discordBot = &DiscordBot{
config: options.Config,
logger: options.Logger,
Session: session,
RealtimeChannel: realtimeChannel,
config: options.Config,
logger: options.Logger,
Session: session,
RelayChannel: relayChannel,
}

return
Expand All @@ -51,7 +82,7 @@ func (bot *DiscordBot) Start() (err error) {
return
}

// Replace all mentions to real name from the message.
// NormalizeDiscordMessage replaces all mentions to real name from the message.
func (bot *DiscordBot) NormalizeDiscordMessage(message string) string {
userRegex := regexp.MustCompile(`<@!?(\d{17,19})>`)
emojiRegex := regexp.MustCompile(`(?:<a?)?:(\w+):(?:\d{18}>)?`)
Expand All @@ -74,7 +105,11 @@ func (bot *DiscordBot) NormalizeDiscordMessage(message string) string {
}

func (bot *DiscordBot) RealtimeChannelSend(message string) (err error) {
_, err = bot.Session.ChannelMessageSend(bot.RealtimeChannel.ID, message)
if bot.RelayChannel == nil {
return
}

_, err = bot.Session.ChannelMessageSend(bot.RelayChannel.ID, message)

return
}
Expand Down

0 comments on commit d6322e2

Please sign in to comment.