Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce API to get Token from discord OAuth2 exchange #41

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env-sample
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,6 @@ IPFS_NODE_URL=https://ipfs.infura.io:5001
ALLOWED_ORIGIN=*
GRAPH_API=https://query.graph.lazarus.network/subgraphs/name/NetSepio
SIGNED_BY=NetSepio
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=
DISCORD_REDIRECT_URL=
14 changes: 7 additions & 7 deletions api/middleware/auth/paseto/paseto.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ func PASETO(c *gin.Context) {
err := c.BindHeader(&headers)
if err != nil {
err = fmt.Errorf("failed to bind header, %s", err)
logValidationFailed(headers.Authorization, err)
logValidationFailed(c.Request.RequestURI, headers.Authorization, err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
if headers.Authorization == "" {
logValidationFailed(headers.Authorization, ErrAuthHeaderMissing)
logValidationFailed(c.Request.RequestURI, headers.Authorization, ErrAuthHeaderMissing)
httphelper.ErrResponse(c, http.StatusBadRequest, ErrAuthHeaderMissing.Error())
c.Abort()
return
Expand All @@ -49,20 +49,20 @@ func PASETO(c *gin.Context) {
if errors.As(err, &validationErr) {
if validationErr.HasExpiredErr() {
err = fmt.Errorf("failed to scan claims for paseto token, %s", err)
logValidationFailed(headers.Authorization, err)
logValidationFailed(c.Request.RequestURI, headers.Authorization, err)
httphelper.CErrResponse(c, http.StatusUnauthorized, customstatuscodes.TokenExpired, "token expired")
c.Abort()
return
}

}
err = fmt.Errorf("failed to scan claims for paseto token, %s", err)
logValidationFailed(headers.Authorization, err)
logValidationFailed(c.Request.RequestURI, headers.Authorization, err)
c.AbortWithStatus(http.StatusUnauthorized)
return
} else {
if err := cc.Valid(); err != nil {
logValidationFailed(headers.Authorization, err)
logValidationFailed(c.Request.RequestURI, headers.Authorization, err)
if err.Error() == gorm.ErrRecordNotFound.Error() {
c.AbortWithStatus(http.StatusUnauthorized)
} else {
Expand All @@ -77,6 +77,6 @@ func PASETO(c *gin.Context) {
}
}

func logValidationFailed(token string, err error) {
logwrapper.Warnf("validation failed with token %v and error: %v", token, err)
func logValidationFailed(api string, token string, err error) {
logwrapper.Warnf("validation failed for api %s with token %v and error: %v", api, token, err)
}
58 changes: 58 additions & 0 deletions api/v1/discordAuth/discordAuth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package discordauth

import (
"context"
"encoding/json"
"io/ioutil"

"github.com/NetSepio/gateway/config/envconfig"
"github.com/NetSepio/gateway/util/pkg/httphelper"
"github.com/NetSepio/gateway/util/pkg/logwrapper"
"github.com/gin-gonic/gin"
"golang.org/x/oauth2"
)

// ApplyRoutes applies router to gin Router
func ApplyRoutes(r *gin.RouterGroup) {
g := r.Group("/discord-auth")
{
g.GET("", discordAuth)
}
}

func discordAuth(c *gin.Context) {
// TODO: validate state
endpoint := oauth2.Endpoint{
AuthURL: "https://discord.com/api/oauth2/authorize",
TokenURL: "https://discord.com/api/oauth2/token",
AuthStyle: oauth2.AuthStyleInParams,
}
conf := &oauth2.Config{
RedirectURL: envconfig.EnvVars.DISCORD_REDIRECT_URL,
ClientID: envconfig.EnvVars.DISCORD_CLIENT_ID,
ClientSecret: envconfig.EnvVars.DISCORD_CLIENT_SECRET,
Scopes: []string{"identify"},
Endpoint: endpoint,
}
token, err := conf.Exchange(context.Background(), c.Request.FormValue("code"))
if err != nil {
logwrapper.Errorf("failed to exchange token: %s", err)
httphelper.ErrResponse(c, 500, "")
return
}
res, err := conf.Client(context.Background(), token).Get("https://discord.com/api/users/@me")
if err != nil {
logwrapper.Errorf("failed to query client: %s", err)
httphelper.ErrResponse(c, 500, "")
return
}
r, err := ioutil.ReadAll(res.Body)
if err != nil {
logwrapper.Errorf("failed to get data from body of exchange token response: %s", err)
httphelper.ErrResponse(c, 500, "")
return
}
var discordRes DicordExchangeRes
json.Unmarshal(r, &discordRes)
httphelper.SuccessResponse(c, "Discord OAuth2 handled", nil)
}
12 changes: 12 additions & 0 deletions api/v1/discordAuth/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package discordauth

type DicordExchangeRes struct {
ID string `json:"id"`
Username string `json:"username"`
Avatar string `json:"avatar"`
Discriminator string `json:"discriminator"`
PublicFlags int `json:"public_flags"`
Flags int `json:"flags"`
Locale string `json:"locale"`
MfaEnabled bool `json:"mfa_enabled"`
}
2 changes: 2 additions & 0 deletions api/v1/v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
authenticate "github.com/NetSepio/gateway/api/v1/authenticate"
claimrole "github.com/NetSepio/gateway/api/v1/claimRole"
delegatereviewcreation "github.com/NetSepio/gateway/api/v1/delegateReviewCreation"
discordauth "github.com/NetSepio/gateway/api/v1/discordAuth"
"github.com/NetSepio/gateway/api/v1/feedback"
flowid "github.com/NetSepio/gateway/api/v1/flowid"
"github.com/NetSepio/gateway/api/v1/healthcheck"
Expand All @@ -25,5 +26,6 @@ func ApplyRoutes(r *gin.RouterGroup) {
delegatereviewcreation.ApplyRoutes(v1)
healthcheck.ApplyRoutes(v1)
feedback.ApplyRoutes(v1)
discordauth.ApplyRoutes(v1)
}
}
3 changes: 3 additions & 0 deletions config/envconfig/envconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ type config struct {
ALLOWED_ORIGIN []string `env:"ALLOWED_ORIGIN,required" envSeparator:","`
GRAPH_API string `env:"GRAPH_API,required"`
SIGNED_BY string `env:"SIGNED_BY,required"`
DISCORD_CLIENT_ID string `env:"DISCORD_CLIENT_ID,required"`
DISCORD_CLIENT_SECRET string `env:"DISCORD_CLIENT_SECRET,required"`
DISCORD_REDIRECT_URL string `env:"DISCORD_REDIRECT_URL,required"`
}

var EnvVars config = config{}
Expand Down
3 changes: 1 addition & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ require (
github.com/ugorji/go v1.2.6 // indirect
github.com/vk-rv/pvx v0.0.0-20210912195928-ac00bc32f6e7
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 // indirect
golang.org/x/sys v0.0.0-20220403205710-6acee93ad0eb // indirect
google.golang.org/protobuf v1.27.1 // indirect
golang.org/x/oauth2 v0.0.0-20220822191816-0ebed06d0094 // indirect
gorm.io/driver/postgres v1.3.8
gorm.io/gorm v1.23.7
)
Loading