Skip to content

Commit

Permalink
Merge branch 'master' into bowen/#280
Browse files Browse the repository at this point in the history
  • Loading branch information
hwbrzzl authored May 8, 2024
2 parents 07addf3 + 1fc0c91 commit f70f514
Show file tree
Hide file tree
Showing 41 changed files with 1,778 additions and 223 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ jobs:
- name: Install dependencies
run: go mod tidy
- name: Lint
uses: golangci/golangci-lint-action@v4
uses: golangci/golangci-lint-action@v6
with:
skip-cache: true
skip-pkg-cache: true
Expand Down
9 changes: 6 additions & 3 deletions auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,9 +231,12 @@ func (a *Auth) Logout() error {
}

func (a *Auth) makeAuthContext(claims *Claims, token string) {
a.ctx.WithValue(ctxKey, Guards{
a.guard: {claims, token},
})
guards, ok := a.ctx.Value(ctxKey).(Guards)
if !ok {
guards = make(Guards)
}
guards[a.guard] = &Guard{claims, token}
a.ctx.WithValue(ctxKey, guards)
}

func (a *Auth) tokenIsDisabled(token string) bool {
Expand Down
83 changes: 76 additions & 7 deletions auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
"github.com/goravel/framework/support/carbon"
)

var guard = "user"
var testUserGuard = "user"

type User struct {
orm.Model
Expand Down Expand Up @@ -109,7 +109,7 @@ func (s *AuthTestSuite) SetupTest() {
s.mockContext = Background()
s.mockOrm = &ormmock.Orm{}
s.mockDB = &ormmock.Query{}
s.auth = NewAuth(guard, s.mockCache, s.mockConfig, s.mockContext, s.mockOrm)
s.auth = NewAuth(testUserGuard, s.mockCache, s.mockConfig, s.mockContext, s.mockOrm)
}

func (s *AuthTestSuite) TestLoginUsingID_EmptySecret() {
Expand Down Expand Up @@ -255,7 +255,7 @@ func (s *AuthTestSuite) TestParse_TokenExpired() {

payload, err := s.auth.Parse(token)
s.Equal(&authcontract.Payload{
Guard: guard,
Guard: testUserGuard,
Key: "1",
ExpireAt: jwt.NewNumericDate(expireAt).Local(),
IssuedAt: jwt.NewNumericDate(issuedAt).Local(),
Expand All @@ -268,7 +268,7 @@ func (s *AuthTestSuite) TestParse_TokenExpired() {
}

func (s *AuthTestSuite) TestParse_InvalidCache() {
auth := NewAuth(guard, nil, s.mockConfig, s.mockContext, s.mockOrm)
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")
Expand All @@ -285,7 +285,7 @@ func (s *AuthTestSuite) TestParse_Success() {

payload, err := s.auth.Parse(token)
s.Equal(&authcontract.Payload{
Guard: guard,
Guard: testUserGuard,
Key: "1",
ExpireAt: jwt.NewNumericDate(carbon.Now().AddMinutes(2).StdTime()).Local(),
IssuedAt: jwt.NewNumericDate(carbon.Now().StdTime()).Local(),
Expand All @@ -307,7 +307,7 @@ func (s *AuthTestSuite) TestParse_SuccessWithPrefix() {

payload, err := s.auth.Parse("Bearer " + token)
s.Equal(&authcontract.Payload{
Guard: guard,
Guard: testUserGuard,
Key: "1",
ExpireAt: jwt.NewNumericDate(carbon.Now().AddMinutes(2).StdTime()).Local(),
IssuedAt: jwt.NewNumericDate(carbon.Now().StdTime()).Local(),
Expand Down Expand Up @@ -454,6 +454,60 @@ func (s *AuthTestSuite) TestUser_Success() {
s.Nil(err)

s.mockConfig.AssertExpectations(s.T())
s.mockCache.AssertExpectations(s.T())
s.mockOrm.AssertExpectations(s.T())
s.mockDB.AssertExpectations(s.T())
}

func (s *AuthTestSuite) TestUser_Success_MultipleParse() {
testAdminGuard := "admin"

s.mockConfig.On("GetString", "jwt.secret").Return("Goravel").Twice()
s.mockConfig.On("GetInt", "jwt.ttl").Return(2).Once()

token1, err := s.auth.LoginUsingID(1)
s.Nil(err)

s.mockConfig.On("GetString", "jwt.secret").Return("Goravel").Twice()
s.mockConfig.On("GetInt", "jwt.ttl").Return(2).Once()

token2, err := s.auth.Guard(testAdminGuard).LoginUsingID(2)
s.Nil(err)

s.mockCache.On("GetBool", "jwt:disabled:"+token1, false).Return(false).Once()

payload, err := s.auth.Parse(token1)
s.Nil(err)
s.NotNil(payload)
s.Equal(testUserGuard, payload.Guard)
s.Equal("1", payload.Key)

s.mockCache.On("GetBool", "jwt:disabled:"+token2, false).Return(false).Once()

payload, err = s.auth.Guard(testAdminGuard).Parse(token2)
s.Nil(err)
s.NotNil(payload)
s.Equal(testAdminGuard, payload.Guard)
s.Equal("2", payload.Key)

var user1 User
s.mockOrm.On("Query").Return(s.mockDB)
s.mockDB.On("FindOrFail", &user1, clause.Eq{Column: clause.PrimaryColumn, Value: "1"}).Return(nil).Once()

err = s.auth.User(&user1)
s.Nil(err)

var user2 User
s.mockOrm.On("Query").Return(s.mockDB)
s.mockDB.On("FindOrFail", &user2, clause.Eq{Column: clause.PrimaryColumn, Value: "2"}).Return(nil).Once()

err = s.auth.Guard(testAdminGuard).User(&user2)
s.Nil(err)

s.mockConfig.AssertExpectations(s.T())
s.mockCache.AssertExpectations(s.T())
s.mockOrm.AssertExpectations(s.T())
s.mockDB.AssertExpectations(s.T())
}

func (s *AuthTestSuite) TestRefresh_NotParse() {
Expand Down Expand Up @@ -528,7 +582,7 @@ func (s *AuthTestSuite) TestRefresh_Success() {
}

func (s *AuthTestSuite) TestLogout_CacheUnsupported() {
s.auth = NewAuth(guard, nil, s.mockConfig, s.mockContext, s.mockOrm)
s.auth = NewAuth(testUserGuard, nil, s.mockConfig, s.mockContext, s.mockOrm)
s.mockConfig.On("GetString", "jwt.secret").Return("Goravel").Once()
s.mockConfig.On("GetInt", "jwt.ttl").Return(2).Once()

Expand Down Expand Up @@ -626,3 +680,18 @@ func (s *AuthTestSuite) TestLogout_Error_TTL_Is_0() {

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

func (s *AuthTestSuite) TestMakeAuthContext() {
testAdminGuard := "admin"

s.auth.makeAuthContext(nil, "1")
guards, ok := s.auth.ctx.Value(ctxKey).(Guards)
s.True(ok)
s.Equal(&Guard{nil, "1"}, guards[testUserGuard])

s.auth.Guard(testAdminGuard).(*Auth).makeAuthContext(nil, "2")
guards, ok = s.auth.ctx.Value(ctxKey).(Guards)
s.True(ok)
s.Equal(&Guard{nil, "1"}, guards[testUserGuard])
s.Equal(&Guard{nil, "2"}, guards[testAdminGuard])
}
2 changes: 2 additions & 0 deletions contracts/database/orm/orm.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ type Query interface {
OrWhereBetween(column string, x, y any) Query
// OrWhereNotBetween adds an "or where column not between x and y" clause to the query.
OrWhereNotBetween(column string, x, y any) Query
// OrWhereNull adds a "or where column is null" clause to the query.
OrWhereNull(column string) Query
// Paginate the given query into a simple paginator.
Paginate(page, limit int, dest any, total *int64) error
// Pluck retrieves a single column from the database.
Expand Down
8 changes: 8 additions & 0 deletions contracts/http/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"net/http"

"github.com/goravel/framework/contracts/filesystem"
"github.com/goravel/framework/contracts/session"
"github.com/goravel/framework/contracts/validation"
)

Expand Down Expand Up @@ -52,6 +53,13 @@ type ContextRequest interface {
// Queries returns all the query string parameters from the request as a map of key-value pairs.
Queries() map[string]string

// HasSession checks if the request has a session.
HasSession() bool
// Session retrieves the session associated with the request.
Session() session.Session
// SetSession sets the session associated with the request.
SetSession(session session.Session) ContextRequest

// Input retrieves data from the request in the following order: JSON, form, query, and route parameters.
Input(key string, defaultValue ...string) string
InputArray(key string, defaultValue ...[]string) []string
Expand Down
2 changes: 1 addition & 1 deletion database/gorm/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func (e *Event) ColumnNamesWithDbColumnNames() map[string]string {
}

func (e *Event) Context() context.Context {
return e.query.instance.Statement.Context
return e.query.ctx
}

func (e *Event) DestOfMap() map[string]any {
Expand Down
13 changes: 11 additions & 2 deletions database/gorm/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,11 @@ func (r *QueryImpl) Select(query any, args ...any) ormcontract.Query {
return r.setConditions(conditions)
}

func (r *QueryImpl) SetContext(ctx context.Context) {
r.ctx = ctx
r.instance.Statement.Context = ctx
}

func (r *QueryImpl) SharedLock() ormcontract.Query {
conditions := r.conditions
conditions.sharedLock = true
Expand Down Expand Up @@ -799,6 +804,10 @@ func (r *QueryImpl) OrWhereNotBetween(column string, x, y any) ormcontract.Query
return r.OrWhere(fmt.Sprintf("%s NOT BETWEEN %v AND %v", column, x, y))
}

func (r *QueryImpl) OrWhereNull(column string) ormcontract.Query {
return r.OrWhere(fmt.Sprintf("%s IS NULL", column))
}

func (r *QueryImpl) WhereNull(column string) ormcontract.Query {
return r.Where(fmt.Sprintf("%s IS NULL", column))
}
Expand Down Expand Up @@ -1181,9 +1190,9 @@ func (r *QueryImpl) event(event ormcontract.EventType, model, dest any) error {
if event, exist := dispatchesEvents.DispatchesEvents()[event]; exist {
return event(instance)
}
}

return nil
return nil
}
}

if observer := observer(dest); observer != nil {
Expand Down
19 changes: 19 additions & 0 deletions database/gorm/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2871,6 +2871,25 @@ func (s *QueryTestSuite) TestWhereNull() {
}
}

func (s *QueryTestSuite) TestOrWhereNull() {
for driver, query := range s.queries {
s.Run(driver.String(), func() {
bio := "or_where_null_bio"
user := User{Name: "or_where_null_user", Avatar: "or_where_null_avatar", Bio: &bio}
s.Nil(query.Create(&user))
s.True(user.ID > 0)

user1 := User{Name: "or_where_null_user_1", Avatar: "or_where_null_avatar_1"}
s.Nil(query.Create(&user1))
s.True(user1.ID > 0)

var users []User
s.Nil(query.Where("name = ?", "or_where_null_user").OrWhereNull("bio").Find(&users))
s.True(len(users) >= 2)
})
}
}

func (s *QueryTestSuite) TestWhereNotNull() {
for driver, query := range s.queries {
s.Run(driver.String(), func() {
Expand Down
20 changes: 16 additions & 4 deletions database/orm.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ func (r *OrmImpl) Connection(name string) ormcontract.Orm {
}

func (r *OrmImpl) DB() (*sql.DB, error) {
db := r.Query().(*databasegorm.QueryImpl)
query := r.Query().(*databasegorm.QueryImpl)

return db.Instance().DB()
return query.Instance().DB()
}

func (r *OrmImpl) Query() ormcontract.Query {
Expand Down Expand Up @@ -106,7 +106,19 @@ func (r *OrmImpl) Transaction(txFunc func(tx ormcontract.Transaction) error) err
}

func (r *OrmImpl) WithContext(ctx context.Context) ormcontract.Orm {
instance, _ := NewOrmImpl(ctx, r.config, r.connection, r.query)
for _, query := range r.queries {
query := query.(*databasegorm.QueryImpl)
query.SetContext(ctx)
}

query := r.query.(*databasegorm.QueryImpl)
query.SetContext(ctx)

return instance
return &OrmImpl{
ctx: ctx,
config: r.config,
connection: r.connection,
query: query,
queries: r.queries,
}
}
8 changes: 4 additions & 4 deletions database/orm/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ type Observer struct {
}

type Model struct {
ID uint `gorm:"primaryKey"`
ID uint `gorm:"primaryKey" json:"id"`
Timestamps
}

type SoftDeletes struct {
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at"`
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at" json:"deleted_at"`
}

type Timestamps struct {
CreatedAt carbon.DateTime `gorm:"autoCreateTime;column:created_at"`
UpdatedAt carbon.DateTime `gorm:"autoUpdateTime;column:updated_at"`
CreatedAt carbon.DateTime `gorm:"autoCreateTime;column:created_at" json:"created_at"`
UpdatedAt carbon.DateTime `gorm:"autoUpdateTime;column:updated_at" json:"updated_at"`
}
Loading

0 comments on commit f70f514

Please sign in to comment.