-
Notifications
You must be signed in to change notification settings - Fork 3
/
routesauthorization.go
75 lines (61 loc) · 1.91 KB
/
routesauthorization.go
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
package main
import (
"fmt"
"github.com/MinecraftHopper/panel/env"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"gorm.io/gorm"
"net/http"
"net/url"
"strings"
)
func login(c *gin.Context) {
state := uuid.New().String()
session := sessions.Default(c)
session.Set("state", state)
_ = session.Save()
u := fmt.Sprintf("https://discord.com/api/oauth2/authorize?response_type=code&client_id=%s&scope=%s&state=%s&redirect_uri=%s",
env.Get("discord.clientid"),
strings.Join([]string{"identify", "guilds"}, "%20"),
state,
url.QueryEscape(env.Get("web.host")+"/login-callback"),
)
c.Redirect(http.StatusTemporaryRedirect, u)
}
func loginCallback(c *gin.Context) {
code := c.Query("code")
state := c.Query("state")
session := sessions.Default(c)
expectedState, ok := session.Get("state").(string)
session.Delete("state")
if !ok || expectedState != state {
c.JSON(http.StatusBadRequest, Error{Message: "missing or invalid state"})
return
}
accessToken, err := redeemCode(code)
if err != nil {
c.JSON(http.StatusInternalServerError, Error{Message: err.Error()})
return
}
userId, err := getUserId(accessToken)
if err != nil {
c.JSON(http.StatusInternalServerError, Error{Message: err.Error()})
return
}
session.Set("discordId", userId)
//for UI help, we'll save off the perms to the client
perms := make([]string, 0)
err = Database.Model(&Permission{}).Where(&Permission{DiscordId: userId}).Select("permission").Find(&perms).Error
if err != nil && gorm.ErrRecordNotFound != err {
c.JSON(http.StatusInternalServerError, Error{Message: err.Error()})
return
}
//perms don't really matter too much in terms of security, so we'll not enforce it being secure
c.SetCookie("perms", strings.Join(perms, "+"), 64000, "/", "", true, false)
_ = session.Save()
c.Redirect(http.StatusTemporaryRedirect, "/")
}
func logout(c *gin.Context) {
sessions.Default(c).Clear()
}