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

Revert "Feat jwt auth" #2

Merged
merged 1 commit into from
Jun 20, 2022
Merged
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
98 changes: 16 additions & 82 deletions auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,40 +7,27 @@ import (
"crypto/rand"
"errors"
"fmt"
"github.com/KnightHacks/knighthacks_shared/models"
"github.com/golang-jwt/jwt"
"github.com/google/go-github/v45/github"
"golang.org/x/oauth2"
"io"
"strconv"
"time"
)

type TokenType string
type Provider int

const (
RefreshTokenType TokenType = "REFRESH"
AccessTokenType TokenType = "ACCESS"
)

var (
TokenNotValid = errors.New("jwt token not valid")
GitHubAuthProvider Provider = iota
GmailAuthProvider Provider = iota
)

type Auth struct {
ConfigMap map[models.Provider]oauth2.Config
signingKey []byte
ConfigMap map[Provider]oauth2.Config
signingKey string
gcm cipher.AEAD
}

type UserClaims struct {
UserID string `json:"user_id"`
Role models.Role `json:"role"`
Type TokenType `json:"type"`
jwt.StandardClaims
}

func NewAuth(signingKey string, cipher32Bit string, configMap map[models.Provider]oauth2.Config) (*Auth, error) {
func NewAuth(signingKey string, cipher32Bit string, configMap map[Provider]oauth2.Config) (*Auth, error) {
newCipher, err := aes.NewCipher([]byte(cipher32Bit))
if err != nil {
return nil, err
Expand All @@ -49,24 +36,25 @@ func NewAuth(signingKey string, cipher32Bit string, configMap map[models.Provide
if err != nil {
return nil, err
}
return &Auth{ConfigMap: configMap, signingKey: []byte(signingKey), gcm: gcm}, nil
return &Auth{ConfigMap: configMap, signingKey: signingKey, gcm: gcm}, nil
}

func (a *Auth) GetAuthCodeURL(provider models.Provider, state string) string {
func (a *Auth) GetAuthCodeURL(provider Provider) string {
config := a.ConfigMap[provider]
return config.AuthCodeURL(state, oauth2.AccessTypeOffline)
// TODO: Implement oauth2 'state' on url to prevent CSRF https://datatracker.ietf.org/doc/html/rfc6749#section-10.12
return config.AuthCodeURL("state", oauth2.AccessTypeOffline)
}

func (a *Auth) ExchangeCode(ctx context.Context, provider models.Provider, code string) (*oauth2.Token, error) {
func (a *Auth) ExchangeCode(ctx context.Context, provider Provider, code string) (*oauth2.Token, error) {
config := a.ConfigMap[provider]
return config.Exchange(ctx, code)
}

func (a *Auth) GetUID(ctx context.Context, provider models.Provider, token string) (string, error) {
func (a *Auth) GetUID(ctx context.Context, provider Provider, token string) (string, error) {
config := a.ConfigMap[provider]
oauthClient := oauth2.NewClient(ctx, config.TokenSource(ctx, &oauth2.Token{AccessToken: token}))

if provider == models.ProviderGithub {
if provider == GitHubAuthProvider {
githubClient := github.NewClient(oauthClient)

user, _, err := githubClient.Users.Get(ctx, "")
Expand Down Expand Up @@ -109,62 +97,8 @@ func (a *Auth) DecryptAccessToken(token string) ([]byte, error) {
return decryptedBytes, nil
}

func (a *Auth) NewTokens(userId string, role models.Role) (refreshToken string, accessToken string, err error) {
refreshToken, err = a.NewRefreshToken(userId, role)
if err != nil {
return "", "", err
}
accessToken, err = a.NewAccessToken(userId, role)
if err != nil {
return "", "", err
}
return refreshToken, accessToken, nil
}

func (a *Auth) NewRefreshToken(userId string, role models.Role) (string, error) {
return a.newJWT(userId, role, RefreshTokenType, time.Hour*24)
}

func (a *Auth) NewAccessToken(userId string, role models.Role) (string, error) {
return a.newJWT(userId, role, AccessTokenType, time.Minute*30)
}

func (a *Auth) newJWT(userId string, role models.Role, tokenType TokenType, expiration time.Duration) (string, error) {
now := time.Now().UTC()
claims := UserClaims{
userId,
role,
tokenType,
jwt.StandardClaims{
ExpiresAt: now.Add(expiration).Unix(),
IssuedAt: now.Unix(),
Issuer: "knighthacks",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
func (a *Auth) NewJWT(mapClaims jwt.MapClaims) (string, error) {
token := jwt.New(jwt.SigningMethodRS256)
token.Claims = mapClaims
return token.SignedString(a.signingKey)
}

func (a *Auth) ParseJWT(tokenString string, tokenType TokenType) (*UserClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return a.signingKey, nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, TokenNotValid
}

if claims, ok := token.Claims.(*UserClaims); ok {
if claims.Type != tokenType {
return nil, fmt.Errorf("you are sending a %s token while we need a %s token", claims.Type, tokenType)
}
return claims, nil
} else {
return nil, errors.New("unable to cast jwt claims to UserClaims")
}
}
69 changes: 0 additions & 69 deletions auth/directives.go

This file was deleted.

36 changes: 0 additions & 36 deletions auth/middleware.go

This file was deleted.

94 changes: 0 additions & 94 deletions models/auth.go

This file was deleted.

30 changes: 0 additions & 30 deletions utils/gin.go

This file was deleted.