Skip to content

Commit

Permalink
simple ui works with link now, auth not uses cookies
Browse files Browse the repository at this point in the history
  • Loading branch information
jokil123 committed Jan 2, 2024
1 parent 285e8c2 commit b68af0d
Show file tree
Hide file tree
Showing 10 changed files with 113 additions and 93 deletions.
8 changes: 4 additions & 4 deletions EsefexApi/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,15 @@ func (api *HttpApi) run() {

router.HandleFunc("/api/sounds/{server_id}", cors(h.GetSounds)).Methods("GET")

router.HandleFunc("/api/server", cors(auth(h.GetServer))).Methods("GET").Headers("User-Token", "")
router.HandleFunc("/api/servers", cors(auth(h.GetServers))).Methods("GET").Headers("User-Token", "")
router.HandleFunc("/api/server", cors(auth(h.GetServer))).Methods("GET").Headers("Cookie", "")
router.HandleFunc("/api/servers", cors(auth(h.GetServers))).Methods("GET").Headers("Cookie", "")

router.HandleFunc("/api/playsound/{user_id}/{server_id}/{sound_id}", cors(h.PostPlaySoundInsecure)).Methods("POST")
router.HandleFunc("/api/playsound/{sound_id}", cors(auth(h.PostPlaySound))).Methods("POST").Headers("User-Token", "")
router.HandleFunc("/api/playsound/{sound_id}", cors(auth(h.PostPlaySound))).Methods("POST").Headers("Cookie", "")

router.HandleFunc("/joinsession/{server_id}", cors(h.GetJoinSession)).Methods("GET")
router.HandleFunc("/link", cors(h.GetLinkDefer)).Methods("GET").Queries("t", "{t}")
router.HandleFunc("/api/link", cors(h.GetLink)).Methods("GET").Queries("t", "{t}")
router.HandleFunc("/api/link", cors(h.GetLinkRedirect)).Methods("GET").Queries("t", "{t}")

router.HandleFunc("/dump", cors(h.GetDump))
router.HandleFunc("/", cors(h.GetIndex)).Methods("GET")
Expand Down
11 changes: 9 additions & 2 deletions EsefexApi/api/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,16 @@ import (
// Auth middleware checks if the user is authenticated and injects the user into the request context
func (m *Middleware) Auth(next func(w http.ResponseWriter, r *http.Request, userID string)) func(w http.ResponseWriter, r *http.Request) {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user_token := r.Header.Get("User-Token")
user_token, err := r.Cookie("User-Token")
if err != nil {
errorMsg := fmt.Sprintf("Error getting user token cookie: %+v", err)

Ouser, err := m.dbs.UserDB.GetUserByToken(userdb.Token(user_token))
log.Println(errorMsg)
http.Error(w, errorMsg, http.StatusUnauthorized)
return
}

Ouser, err := m.dbs.UserDB.GetUserByToken(userdb.Token(user_token.Value))
if err != nil || Ouser.IsNone() {
errorMsg := fmt.Sprintf("Error getting user by token: %+v", err)

Expand Down
3 changes: 1 addition & 2 deletions EsefexApi/api/public/simpleui/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
<body>
<h1>Esefex Simple UI</h1>
<p>Simple UI for Esefex for Dev Purposes</p>
<label for="userTokenInput">User-Token</label>
<input type="password" id="userTokenInput" placeholder="User-Token">
<button onclick="location.reload()">Reload</button>
<h2>Sounds</h2>
<div id="sounds"></div>
</body>
Expand Down
23 changes: 4 additions & 19 deletions EsefexApi/api/public/simpleui/index.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
async function init() {
const soundsDiv = document.getElementById('sounds');
const userTokenInput = document.getElementById('userTokenInput');
userTokenInput.value = document.cookie.split('; ').find(row => row.startsWith('User-Token')).split('=')[1];

userTokenInput.addEventListener('change', (e) => {
setUserToken(e.target.value);
});

let serverRequest = await fetch('/api/server', {
method: 'GET',
headers: {
'User-Token': userTokenInput.value
}
credentials: 'same-origin',
});

if (serverRequest.status != 200) {
Expand All @@ -23,9 +16,7 @@ async function init() {

let soundsRequest = await fetch(`/api/sounds/${await serverRequest.text()}`, {
method: 'GET',
headers: {
'User-Token': userTokenInput.value
}
credentials: 'same-origin',
});
let sounds = await soundsRequest.json();

Expand All @@ -35,17 +26,11 @@ async function init() {
soundButton.addEventListener('click', async () => {
await fetch(`/api/playsound/${sound.id}`, {
method: 'POST',
headers: {
'User-Token': userTokenInput.value
}
credentials: 'same-origin',
});
});
soundsDiv.appendChild(soundButton);
});
}

function setUserToken(token) {
document.cookie = `User-Token=${token}`;
}

init();
init();
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@ package routes

import (
"fmt"
"html/template"
"log"
"net/http"
)

type LinkRedirect struct {
RedirectUrl string
}

// api/link?<server_id>
func (h *RouteHandlers) GetLink(w http.ResponseWriter, r *http.Request) {
func (h *RouteHandlers) GetLinkRedirect(w http.ResponseWriter, r *http.Request) {
linkToken := r.URL.Query().Get("t")

if linkToken == "" {
Expand All @@ -33,23 +38,33 @@ func (h *RouteHandlers) GetLink(w http.ResponseWriter, r *http.Request) {
return
}

redirectUrl := fmt.Sprintf("%s://link/%s", h.cProto, userToken)
response := fmt.Sprintf(`<meta http-equiv="refresh" content="0; URL=%s" />`, redirectUrl)
fmt.Fprint(w, response)

cookie := http.Cookie{
Name: "User-Token",
Value: string(userToken),
Path: "/",
MaxAge: 0,
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
SameSite: http.SameSiteDefaultMode,
}
http.SetCookie(w, &cookie)

w.Header().Set("Content-Type", "text/html")

tmpl, err := template.ParseFiles("./api/templates/linkredirect.html")
if err != nil {
http.Error(w, "Error parsing template", http.StatusInternalServerError)
return
}

err = tmpl.Execute(w, LinkRedirect{
RedirectUrl: fmt.Sprintf("%s://link/%s", h.cProto, userToken),
})
if err != nil {
http.Error(w, "Error executing template", http.StatusInternalServerError)
return
}

h.dbs.LinkTokenStore.DeleteToken(userID)

log.Printf("got /joinsession request\n")
Expand Down
40 changes: 40 additions & 0 deletions EsefexApi/api/templates/linkredirect.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="refresh" content="0; URL={{.RedirectUrl}}" />
<title>Redirecting...</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
background-color: #f5f5f5;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #333;
}

h1 {
font-size: 3rem;
margin-top: 20px;
margin-bottom: 10px;
}

button {
margin-top: 10px;
height: 3rem;
width: 10rem;
font-size: 1rem;
color: #333;
}
</style>
</head>
<body>
<h1>Not Redirecting?</h1>
<p>Click the button below to open the link in the web app instead.</p>
<button onclick="window.location.href='/static/simpleui';"><b>Open In Web App Instead</b></button>
</body>
</html>
5 changes: 2 additions & 3 deletions EsefexApi/audioplayer/discordplayer/discordplayer.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func NewDiscordPlayer(ds *discordgo.Session, dbs *db.Databases, useTimeouts bool

ds.AddHandler(func(s *discordgo.Session, e *discordgo.VoiceStateUpdate) {
// check if previous state has a vcon associated with it and close it, make sure that it is not closed twice
if e.BeforeUpdate == nil {
if e.BeforeUpdate == nil || e.ChannelID != "" {
return
}

Expand All @@ -76,13 +76,12 @@ func NewDiscordPlayer(ds *discordgo.Session, dbs *db.Databases, useTimeouts bool
return
}

log.Printf("Users in channel: %d", len(users))
// log.Printf("Users in channel: %d", len(users))

if len(users) == 1 {
log.Printf("Channel empty, closing vcon: %s", e.BeforeUpdate.ChannelID)
dp.UnregisterVcon(e.BeforeUpdate.ChannelID)
}

})

return dp
Expand Down
6 changes: 3 additions & 3 deletions EsefexApi/bot/commands/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,6 @@ func NewCommandHandlers(dbs *db.Databases, domain string) *CommandHandlers {
ch.Commands["upload"] = UploadCommand
ch.Handlers["upload"] = WithErrorHandling(ch.Upload)

ch.Commands["session"] = SessionCommand
ch.Handlers["session"] = WithErrorHandling(ch.Session)

ch.Commands["list"] = ListCommand
ch.Handlers["list"] = WithErrorHandling(ch.List)

Expand All @@ -38,6 +35,9 @@ func NewCommandHandlers(dbs *db.Databases, domain string) *CommandHandlers {
ch.Commands["link"] = LinkCommand
ch.Handlers["link"] = WithErrorHandling(ch.Link)

ch.Commands["unlink"] = UnlinkCommand
ch.Handlers["unlink"] = WithErrorHandling(ch.Unlink)

return ch
}

Expand Down
54 changes: 0 additions & 54 deletions EsefexApi/bot/commands/session.go

This file was deleted.

29 changes: 29 additions & 0 deletions EsefexApi/bot/commands/unlink.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package commands

import (
"esefexapi/userdb"

"github.com/bwmarrin/discordgo"
)

var (
UnlinkCommand = &discordgo.ApplicationCommand{
Name: "unlink",
Description: "Unlink your Discord account from Esefex. Useful if you think your account has been compromised.",
}
)

func (c *CommandHandlers) Unlink(s *discordgo.Session, i *discordgo.InteractionCreate) (*discordgo.InteractionResponse, error) {
c.dbs.UserDB.DeleteUser(i.Member.User.ID)
c.dbs.UserDB.SetUser(userdb.User{
ID: i.Member.User.ID,
Tokens: []userdb.Token{},
})

return &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Your account has been unlinked from Esefex. You can now link your account again.",
},
}, nil
}

0 comments on commit b68af0d

Please sign in to comment.