Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
10e3e26
add new errors in auth module
kkumar-gcc Oct 3, 2024
c2381bf
Merge branch 'master' into kkumar-gcc/define-errors
kkumar-gcc Oct 5, 2024
e02f2ef
add custom errors for cache
kkumar-gcc Oct 5, 2024
c61e59c
add custom errors for console
kkumar-gcc Oct 5, 2024
635a02d
add custom errors for crypt
kkumar-gcc Oct 5, 2024
ac22199
add custom errors for crypt
kkumar-gcc Oct 5, 2024
b3fcb03
add custom errors for event
kkumar-gcc Oct 5, 2024
96f00eb
add custom errors for facade
kkumar-gcc Oct 5, 2024
a29c1dc
optimize cache
kkumar-gcc Oct 5, 2024
446cfab
add custom errors for filesystem
kkumar-gcc Oct 5, 2024
0efda3d
add custom errors for filesystem
kkumar-gcc Oct 5, 2024
9a86a82
add custom errors for hash
kkumar-gcc Oct 5, 2024
734cc25
add custom errors for log
kkumar-gcc Oct 5, 2024
c46fdb8
add custom errors for lang
kkumar-gcc Oct 5, 2024
8fad98c
add custom errors for validation
kkumar-gcc Oct 5, 2024
f43a21e
add custom errors for testing
kkumar-gcc Oct 5, 2024
15f0f16
add custom errors for schedule
kkumar-gcc Oct 5, 2024
20c8cdb
add custom errors for route
kkumar-gcc Oct 5, 2024
b9de879
add custom errors for queue
kkumar-gcc Oct 5, 2024
787ef50
add custom errors for database
kkumar-gcc Oct 5, 2024
d6040cb
fix:test
kkumar-gcc Oct 5, 2024
a5ab76f
fix:test
kkumar-gcc Oct 5, 2024
1dbb3a7
fix:test
kkumar-gcc Oct 5, 2024
2eddca4
fix:test
kkumar-gcc Oct 5, 2024
a914261
fix:test
kkumar-gcc Oct 5, 2024
33ddb6f
fix:test
kkumar-gcc Oct 5, 2024
73478d8
Merge branch 'master' into kkumar-gcc/define-errors
kkumar-gcc Oct 5, 2024
2cbcfc7
reorder errors message and remove Err prefix
kkumar-gcc Oct 6, 2024
203d78e
.
kkumar-gcc Oct 6, 2024
4d93eb2
.
kkumar-gcc Oct 6, 2024
6af8080
update cache driver
kkumar-gcc Oct 6, 2024
28066a7
update cache driver
kkumar-gcc Oct 6, 2024
2cfca6b
Merge branch 'master' into kkumar-gcc/define-errors
kkumar-gcc Oct 6, 2024
32570f8
remove unused errors.go
kkumar-gcc Oct 6, 2024
bdef0b4
Merge remote-tracking branch 'origin/kkumar-gcc/define-errors' into k…
kkumar-gcc Oct 6, 2024
920e9fd
add errors to support console
kkumar-gcc Oct 6, 2024
0f04d58
add errors for support/file
kkumar-gcc Oct 13, 2024
e0e51b5
Merge branch 'master' into kkumar-gcc/define-errors
kkumar-gcc Oct 14, 2024
8ee68fa
Merge branch 'master' into kkumar-gcc/define-errors
kkumar-gcc Oct 14, 2024
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
44 changes: 22 additions & 22 deletions auth/auth.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package auth

import (
"errors"
"strings"
"time"

Expand All @@ -14,6 +13,7 @@ import (
"github.com/goravel/framework/contracts/config"
"github.com/goravel/framework/contracts/database/orm"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/errors"
"github.com/goravel/framework/support/carbon"
"github.com/goravel/framework/support/database"
)
Expand Down Expand Up @@ -58,16 +58,16 @@ func (a *Auth) Guard(name string) contractsauth.Auth {
func (a *Auth) User(user any) error {
auth, ok := a.ctx.Value(ctxKey).(Guards)
if !ok || auth[a.guard] == nil {
return ErrorParseTokenFirst
return errors.ErrAuthParseTokenFirst
}
if auth[a.guard].Claims == nil {
return ErrorParseTokenFirst
return errors.ErrAuthParseTokenFirst
}
if auth[a.guard].Claims.Key == "" {
return ErrorInvalidKey
return errors.ErrAuthInvalidKey
}
if auth[a.guard].Token == "" {
return ErrorTokenExpired
return errors.ErrAuthTokenExpired
}
if err := a.orm.Query().FindOrFail(user, clause.Eq{Column: clause.PrimaryColumn, Value: auth[a.guard].Claims.Key}); err != nil {
return err
Expand All @@ -79,10 +79,10 @@ func (a *Auth) User(user any) error {
func (a *Auth) Id() (string, error) {
auth, ok := a.ctx.Value(ctxKey).(Guards)
if !ok || auth[a.guard] == nil {
return "", ErrorParseTokenFirst
return "", errors.ErrAuthParseTokenFirst
}
if auth[a.guard].Token == "" {
return "", ErrorTokenExpired
return "", errors.ErrAuthTokenExpired
}

return auth[a.guard].Claims.Key, nil
Expand All @@ -91,10 +91,10 @@ func (a *Auth) Id() (string, error) {
func (a *Auth) Parse(token string) (*contractsauth.Payload, error) {
token = strings.ReplaceAll(token, "Bearer ", "")
if a.cache == nil {
return nil, errors.New("cache support is required")
return nil, errors.ErrCacheSupportRequired.SetModule(errors.ModuleAuth)
}
if a.tokenIsDisabled(token) {
return nil, ErrorTokenDisabled
return nil, errors.ErrAuthTokenDisabled
}

jwtSecret := a.config.GetString("jwt.secret")
Expand All @@ -107,7 +107,7 @@ func (a *Auth) Parse(token string) (*contractsauth.Payload, error) {
if errors.Is(err, jwt.ErrTokenExpired) && tokenClaims != nil {
claims, ok := tokenClaims.Claims.(*Claims)
if !ok {
return nil, ErrorInvalidClaims
return nil, errors.ErrAuthInvalidClaims
}

a.makeAuthContext(claims, "")
Expand All @@ -117,18 +117,18 @@ func (a *Auth) Parse(token string) (*contractsauth.Payload, error) {
Key: claims.Key,
ExpireAt: claims.ExpiresAt.Local(),
IssuedAt: claims.IssuedAt.Local(),
}, ErrorTokenExpired
}, errors.ErrAuthTokenExpired
}

return nil, ErrorInvalidToken
return nil, errors.ErrAuthInvalidToken
}
if tokenClaims == nil || !tokenClaims.Valid {
return nil, ErrorInvalidToken
return nil, errors.ErrAuthInvalidToken
}

claims, ok := tokenClaims.Claims.(*Claims)
if !ok {
return nil, ErrorInvalidClaims
return nil, errors.ErrAuthInvalidClaims
}

a.makeAuthContext(claims, token)
Expand All @@ -144,7 +144,7 @@ func (a *Auth) Parse(token string) (*contractsauth.Payload, error) {
func (a *Auth) Login(user any) (token string, err error) {
id := database.GetID(user)
if id == nil {
return "", ErrorNoPrimaryKeyField
return "", errors.ErrAuthNoPrimaryKeyField
}

return a.LoginUsingID(id)
Expand All @@ -153,7 +153,7 @@ func (a *Auth) Login(user any) (token string, err error) {
func (a *Auth) LoginUsingID(id any) (token string, err error) {
jwtSecret := a.config.GetString("jwt.secret")
if jwtSecret == "" {
return "", ErrorEmptySecret
return "", errors.ErrAuthEmptySecret
}

nowTime := carbon.Now()
Expand All @@ -165,7 +165,7 @@ func (a *Auth) LoginUsingID(id any) (token string, err error) {
expireTime := nowTime.AddMinutes(ttl).StdTime()
key := cast.ToString(id)
if key == "" {
return "", ErrorInvalidKey
return "", errors.ErrAuthInvalidKey
}
claims := Claims{
key,
Expand All @@ -191,10 +191,10 @@ func (a *Auth) LoginUsingID(id any) (token string, err error) {
func (a *Auth) Refresh() (token string, err error) {
auth, ok := a.ctx.Value(ctxKey).(Guards)
if !ok || auth[a.guard] == nil {
return "", ErrorParseTokenFirst
return "", errors.ErrAuthParseTokenFirst
}
if auth[a.guard].Claims == nil {
return "", ErrorParseTokenFirst
return "", errors.ErrAuthParseTokenFirst
}

nowTime := carbon.Now()
Expand All @@ -206,7 +206,7 @@ func (a *Auth) Refresh() (token string, err error) {

expireTime := carbon.FromStdTime(auth[a.guard].Claims.ExpiresAt.Time).AddMinutes(refreshTtl)
if nowTime.Gt(expireTime) {
return "", ErrorRefreshTimeExceeded
return "", errors.ErrAuthRefreshTimeExceeded
}

return a.LoginUsingID(auth[a.guard].Claims.Key)
Expand All @@ -219,13 +219,13 @@ func (a *Auth) Logout() error {
}

if a.cache == nil {
return errors.New("cache support is required")
return errors.ErrCacheSupportRequired.SetModule(errors.ModuleAuth)
}

ttl := a.config.GetInt("jwt.ttl")
if ttl == 0 {
if ok := a.cache.Forever(getDisabledCacheKey(auth[a.guard].Token), true); !ok {
return errors.New("cache forever failed")
return errors.ErrCacheForeverFailed.SetModule(errors.ModuleAuth)
}
} else {
if err := a.cache.Put(getDisabledCacheKey(auth[a.guard].Token),
Expand Down
42 changes: 21 additions & 21 deletions auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package auth

import (
"context"
"errors"
"sync"
"testing"
"time"
Expand All @@ -15,6 +14,7 @@ import (
authcontract "github.com/goravel/framework/contracts/auth"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/database/orm"
"github.com/goravel/framework/errors"
cachemock "github.com/goravel/framework/mocks/cache"
configmock "github.com/goravel/framework/mocks/config"
ormmock "github.com/goravel/framework/mocks/database/orm"
Expand Down Expand Up @@ -117,7 +117,7 @@ func (s *AuthTestSuite) TestLoginUsingID_EmptySecret() {

token, err := s.auth.LoginUsingID(1)
s.Empty(token)
s.ErrorIs(err, ErrorEmptySecret)
s.ErrorIs(err, errors.ErrAuthEmptySecret)

s.mockConfig.AssertExpectations(s.T())
}
Expand All @@ -128,7 +128,7 @@ func (s *AuthTestSuite) TestLoginUsingID_InvalidKey() {

token, err := s.auth.LoginUsingID("")
s.Empty(token)
s.ErrorIs(err, ErrorInvalidKey)
s.ErrorIs(err, errors.ErrAuthInvalidKey)

s.mockConfig.AssertExpectations(s.T())
}
Expand Down Expand Up @@ -198,7 +198,7 @@ func (s *AuthTestSuite) TestLogin_ErrorModel() {
errorUser.Name = "Goravel"
token, err := s.auth.Login(&errorUser)
s.Empty(token)
s.EqualError(err, "the primaryKey field was not found in the model, set primaryKey like orm.Model")
s.EqualError(err, errors.ErrAuthNoPrimaryKeyField.Error())
}

func (s *AuthTestSuite) TestLogin_NoPrimaryKey() {
Expand All @@ -212,7 +212,7 @@ func (s *AuthTestSuite) TestLogin_NoPrimaryKey() {
user.Name = "Goravel"
token, err := s.auth.Login(&user)
s.Empty(token)
s.ErrorIs(err, ErrorNoPrimaryKeyField)
s.ErrorIs(err, errors.ErrAuthNoPrimaryKeyField)
}

func (s *AuthTestSuite) TestParse_TokenDisabled() {
Expand All @@ -221,7 +221,7 @@ func (s *AuthTestSuite) TestParse_TokenDisabled() {

payload, err := s.auth.Parse(token)
s.Nil(payload)
s.EqualError(err, "token is disabled")
s.EqualError(err, errors.ErrAuthTokenDisabled.Error())
}

func (s *AuthTestSuite) TestParse_TokenInvalid() {
Expand Down Expand Up @@ -260,7 +260,7 @@ func (s *AuthTestSuite) TestParse_TokenExpired() {
ExpireAt: jwt.NewNumericDate(expireAt).Local(),
IssuedAt: jwt.NewNumericDate(issuedAt).Local(),
}, payload)
s.ErrorIs(err, ErrorTokenExpired)
s.ErrorIs(err, errors.ErrAuthTokenExpired)

carbon.UnsetTestNow()

Expand All @@ -271,7 +271,7 @@ func (s *AuthTestSuite) TestParse_InvalidCache() {
auth := NewAuth(testUserGuard, nil, s.mockConfig, s.mockContext, s.mockOrm)
payload, err := auth.Parse("1")
s.Nil(payload)
s.EqualError(err, "cache support is required")
s.EqualError(err, errors.ErrCacheSupportRequired.SetModule(errors.ModuleAuth).Error())
}

func (s *AuthTestSuite) TestParse_Success() {
Expand Down Expand Up @@ -326,15 +326,15 @@ func (s *AuthTestSuite) TestParse_ExpiredAndInvalid() {
s.mockCache.On("GetBool", "jwt:disabled:"+token, false).Return(false).Once()

_, err := s.auth.Parse(token)
s.ErrorIs(err, ErrorInvalidToken)
s.ErrorIs(err, errors.ErrAuthInvalidToken)

s.mockConfig.AssertExpectations(s.T())
}

func (s *AuthTestSuite) TestUser_NoParse() {
var user User
err := s.auth.User(user)
s.EqualError(err, "parse token first")
s.EqualError(err, errors.ErrAuthParseTokenFirst.Error())

s.mockConfig.AssertExpectations(s.T())
}
Expand Down Expand Up @@ -380,7 +380,7 @@ func (s *AuthTestSuite) TestID_TokenExpired() {

// Parse the token
_, err = s.auth.Parse(token)
s.ErrorIs(err, ErrorTokenExpired)
s.ErrorIs(err, errors.ErrAuthTokenExpired)

// Now, call the ID method and expect it to return an empty value
id, _ := s.auth.Id()
Expand All @@ -397,7 +397,7 @@ func (s *AuthTestSuite) TestID_TokenInvalid() {
s.mockCache.On("GetBool", "jwt:disabled:"+token, false).Return(false).Once()

_, err := s.auth.Parse(token)
s.ErrorIs(err, ErrorInvalidToken)
s.ErrorIs(err, errors.ErrAuthInvalidToken)

id, _ := s.auth.Id()
s.Empty(id)
Expand Down Expand Up @@ -441,11 +441,11 @@ func (s *AuthTestSuite) TestUser_Expired() {

payload, err := s.auth.Parse(token)
s.NotNil(payload)
s.ErrorIs(err, ErrorTokenExpired)
s.ErrorIs(err, errors.ErrAuthTokenExpired)

var user User
err = s.auth.User(&user)
s.EqualError(err, "token expired")
s.EqualError(err, errors.ErrAuthTokenExpired.Error())

s.mockConfig.On("GetInt", "jwt.refresh_ttl").Return(2).Once()

Expand Down Expand Up @@ -478,19 +478,19 @@ func (s *AuthTestSuite) TestUser_RefreshExpired() {

payload, err := s.auth.Parse(token)
s.NotNil(payload)
s.ErrorIs(err, ErrorTokenExpired)
s.ErrorIs(err, errors.ErrAuthTokenExpired)

var user User
err = s.auth.User(&user)
s.EqualError(err, "token expired")
s.EqualError(err, errors.ErrAuthTokenExpired.Error())

s.mockConfig.On("GetInt", "jwt.refresh_ttl").Return(1).Once()

carbon.SetTestNow(carbon.Now().AddMinutes(2))

token, err = s.auth.Refresh()
s.Empty(token)
s.EqualError(err, "refresh time exceeded")
s.EqualError(err, errors.ErrAuthRefreshTimeExceeded.Error())

carbon.UnsetTestNow()

Expand Down Expand Up @@ -577,7 +577,7 @@ func (s *AuthTestSuite) TestUser_Success_MultipleParse() {
func (s *AuthTestSuite) TestRefresh_NotParse() {
token, err := s.auth.Refresh()
s.Empty(token)
s.EqualError(err, "parse token first")
s.EqualError(err, errors.ErrAuthParseTokenFirst.Error())

s.mockConfig.AssertExpectations(s.T())
}
Expand All @@ -602,7 +602,7 @@ func (s *AuthTestSuite) TestRefresh_RefreshTimeExceeded() {

token, err = s.auth.Refresh()
s.Empty(token)
s.EqualError(err, "refresh time exceeded")
s.EqualError(err, errors.ErrAuthRefreshTimeExceeded.Error())

carbon.UnsetTestNow()

Expand Down Expand Up @@ -653,7 +653,7 @@ func (s *AuthTestSuite) TestLogout_CacheUnsupported() {
token, err := s.auth.LoginUsingID(1)
s.NotEmpty(token)
s.Nil(err)
s.EqualError(s.auth.Logout(), "cache support is required")
s.EqualError(s.auth.Logout(), errors.ErrCacheSupportRequired.SetModule(errors.ModuleAuth).Error())

s.mockConfig.AssertExpectations(s.T())
}
Expand Down Expand Up @@ -740,7 +740,7 @@ func (s *AuthTestSuite) TestLogout_Error_TTL_Is_0() {

s.mockCache.On("Forever", testifymock.Anything, true).Return(false).Once()

s.EqualError(s.auth.Logout(), "cache forever failed")
s.EqualError(s.auth.Logout(), errors.ErrCacheForeverFailed.SetModule(errors.ModuleAuth).Error())

s.mockConfig.AssertExpectations(s.T())
}
Expand Down
17 changes: 0 additions & 17 deletions auth/errors.go

This file was deleted.

16 changes: 15 additions & 1 deletion auth/service_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
contractconsole "github.com/goravel/framework/contracts/console"
"github.com/goravel/framework/contracts/foundation"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/errors"
)

const BindingAuth = "goravel.auth"
Expand All @@ -19,8 +20,21 @@ type ServiceProvider struct {
func (database *ServiceProvider) Register(app foundation.Application) {
app.BindWith(BindingAuth, func(app foundation.Application, parameters map[string]any) (any, error) {
config := app.MakeConfig()
if config == nil {
return nil, errors.ErrConfigFacadeNotSet.SetModule(errors.ModuleAuth)
}
cacheFacade := app.MakeCache()
if cacheFacade == nil {
return nil, errors.ErrCacheFacadeNotSet.SetModule(errors.ModuleAuth)
}

ormFacade := app.MakeOrm()
if ormFacade == nil {
return nil, errors.ErrOrmFacadeNotSet.SetModule(errors.ModuleAuth)
}

return NewAuth(config.GetString("auth.defaults.guard"),
app.MakeCache(), config, parameters["ctx"].(http.Context), app.MakeOrm()), nil
cacheFacade, config, parameters["ctx"].(http.Context), ormFacade), nil
})
app.Singleton(BindingGate, func(app foundation.Application) (any, error) {
return access.NewGate(context.Background()), nil
Expand Down
Loading
Loading