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

[#120] Implement IoC Container #115

Merged
merged 26 commits into from
May 24, 2023
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
4 changes: 2 additions & 2 deletions auth/access/gate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import (
"fmt"
"testing"

"github.com/goravel/framework/contracts/auth/access"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"

"github.com/goravel/framework/contracts/auth/access"
)

type contextKey int
Expand Down
90 changes: 49 additions & 41 deletions auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ import (
"gorm.io/gorm/clause"

contractsauth "github.com/goravel/framework/contracts/auth"
"github.com/goravel/framework/contracts/cache"
"github.com/goravel/framework/contracts/config"
"github.com/goravel/framework/contracts/database/orm"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All of the modules shouldn't be dependent on facades and should inject if needed.

"github.com/goravel/framework/support/database"
supporttime "github.com/goravel/framework/support/time"
)
Expand All @@ -35,53 +37,59 @@ type Guard struct {
type Guards map[string]*Guard

type Auth struct {
guard string
cache cache.Cache
config config.Config
guard string
orm orm.Orm
}

func NewAuth(guard string) *Auth {
func NewAuth(guard string, cache cache.Cache, config config.Config, orm orm.Orm) *Auth {
jwt.TimeFunc = supporttime.Now

return &Auth{
guard: guard,
cache: cache,
config: config,
guard: guard,
orm: orm,
}
}

func (app *Auth) Guard(name string) contractsauth.Auth {
return NewAuth(name)
func (a *Auth) Guard(name string) contractsauth.Auth {
return NewAuth(name, a.cache, a.config, a.orm)
}

//User need parse token first.
func (app *Auth) User(ctx http.Context, user any) error {
func (a *Auth) User(ctx http.Context, user any) error {
auth, ok := ctx.Value(ctxKey).(Guards)
if !ok || auth[app.guard] == nil {
if !ok || auth[a.guard] == nil {
return ErrorParseTokenFirst
}
if auth[app.guard].Claims == nil {
if auth[a.guard].Claims == nil {
return ErrorParseTokenFirst
}
if auth[app.guard].Claims.Key == "" {
if auth[a.guard].Claims.Key == "" {
return ErrorInvalidKey
}
if auth[app.guard].Token == "" {
if auth[a.guard].Token == "" {
return ErrorTokenExpired
}
if err := facades.Orm.Query().Find(user, clause.Eq{Column: clause.PrimaryColumn, Value: auth[app.guard].Claims.Key}); err != nil {
if err := a.orm.Query().Find(user, clause.Eq{Column: clause.PrimaryColumn, Value: auth[a.guard].Claims.Key}); err != nil {
return err
}

return nil
}

func (app *Auth) Parse(ctx http.Context, token string) (*contractsauth.Payload, error) {
func (a *Auth) Parse(ctx http.Context, token string) (*contractsauth.Payload, error) {
token = strings.ReplaceAll(token, "Bearer ", "")
if facades.Cache == nil {
if a.cache == nil {
return nil, errors.New("cache support is required")
}
if tokenIsDisabled(token) {
if a.tokenIsDisabled(token) {
return nil, ErrorTokenDisabled
}

jwtSecret := facades.Config.GetString("jwt.secret")
jwtSecret := a.config.GetString("jwt.secret")
tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (any, error) {
return []byte(jwtSecret), nil
})
Expand All @@ -92,7 +100,7 @@ func (app *Auth) Parse(ctx http.Context, token string) (*contractsauth.Payload,
return nil, ErrorInvalidClaims
}

app.makeAuthContext(ctx, claims, "")
a.makeAuthContext(ctx, claims, "")

return &contractsauth.Payload{
Guard: claims.Subject,
Expand All @@ -113,7 +121,7 @@ func (app *Auth) Parse(ctx http.Context, token string) (*contractsauth.Payload,
return nil, ErrorInvalidClaims
}

app.makeAuthContext(ctx, claims, token)
a.makeAuthContext(ctx, claims, token)

return &contractsauth.Payload{
Guard: claims.Subject,
Expand All @@ -123,23 +131,23 @@ func (app *Auth) Parse(ctx http.Context, token string) (*contractsauth.Payload,
}, nil
}

func (app *Auth) Login(ctx http.Context, user any) (token string, err error) {
func (a *Auth) Login(ctx http.Context, user any) (token string, err error) {
id := database.GetID(user)
if id == nil {
return "", ErrorNoPrimaryKeyField
}

return app.LoginUsingID(ctx, id)
return a.LoginUsingID(ctx, id)
}

func (app *Auth) LoginUsingID(ctx http.Context, id any) (token string, err error) {
jwtSecret := facades.Config.GetString("jwt.secret")
func (a *Auth) LoginUsingID(ctx http.Context, id any) (token string, err error) {
jwtSecret := a.config.GetString("jwt.secret")
if jwtSecret == "" {
return "", ErrorEmptySecret
}

nowTime := supporttime.Now()
ttl := facades.Config.GetInt("jwt.ttl")
ttl := a.config.GetInt("jwt.ttl")
expireTime := nowTime.Add(time.Duration(ttl) * unit)
key := cast.ToString(id)
if key == "" {
Expand All @@ -150,7 +158,7 @@ func (app *Auth) LoginUsingID(ctx http.Context, id any) (token string, err error
jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(expireTime),
IssuedAt: jwt.NewNumericDate(nowTime),
Subject: app.guard,
Subject: a.guard,
},
}

Expand All @@ -160,62 +168,62 @@ func (app *Auth) LoginUsingID(ctx http.Context, id any) (token string, err error
return "", err
}

app.makeAuthContext(ctx, &claims, token)
a.makeAuthContext(ctx, &claims, token)

return
}

//Refresh need parse token first.
func (app *Auth) Refresh(ctx http.Context) (token string, err error) {
func (a *Auth) Refresh(ctx http.Context) (token string, err error) {
auth, ok := ctx.Value(ctxKey).(Guards)
if !ok || auth[app.guard] == nil {
if !ok || auth[a.guard] == nil {
return "", ErrorParseTokenFirst
}
if auth[app.guard].Claims == nil {
if auth[a.guard].Claims == nil {
return "", ErrorParseTokenFirst
}

nowTime := supporttime.Now()
refreshTtl := facades.Config.GetInt("jwt.refresh_ttl")
expireTime := auth[app.guard].Claims.ExpiresAt.Add(time.Duration(refreshTtl) * unit)
refreshTtl := a.config.GetInt("jwt.refresh_ttl")
expireTime := auth[a.guard].Claims.ExpiresAt.Add(time.Duration(refreshTtl) * unit)
if nowTime.Unix() > expireTime.Unix() {
return "", ErrorRefreshTimeExceeded
}

return app.LoginUsingID(ctx, auth[app.guard].Claims.Key)
return a.LoginUsingID(ctx, auth[a.guard].Claims.Key)
}

func (app *Auth) Logout(ctx http.Context) error {
func (a *Auth) Logout(ctx http.Context) error {
auth, ok := ctx.Value(ctxKey).(Guards)
if !ok || auth[app.guard] == nil || auth[app.guard].Token == "" {
if !ok || auth[a.guard] == nil || auth[a.guard].Token == "" {
return nil
}

if facades.Cache == nil {
if a.cache == nil {
return errors.New("cache support is required")
}

if err := facades.Cache.Put(getDisabledCacheKey(auth[app.guard].Token),
if err := a.cache.Put(getDisabledCacheKey(auth[a.guard].Token),
true,
time.Duration(facades.Config.GetInt("jwt.ttl"))*unit,
time.Duration(a.config.GetInt("jwt.ttl"))*unit,
); err != nil {
return err
}

delete(auth, app.guard)
delete(auth, a.guard)
ctx.WithValue(ctxKey, auth)

return nil
}

func (app *Auth) makeAuthContext(ctx http.Context, claims *Claims, token string) {
func (a *Auth) makeAuthContext(ctx http.Context, claims *Claims, token string) {
ctx.WithValue(ctxKey, Guards{
app.guard: {claims, token},
a.guard: {claims, token},
})
}

func tokenIsDisabled(token string) bool {
return facades.Cache.GetBool(getDisabledCacheKey(token), false)
func (a *Auth) tokenIsDisabled(token string) bool {
return a.cache.GetBool(getDisabledCacheKey(token), false)
}

func getDisabledCacheKey(token string) string {
Expand Down
Loading