Skip to content

Commit

Permalink
feat: Keycloak role permissions system
Browse files Browse the repository at this point in the history
  • Loading branch information
dogukanoksuz committed Sep 10, 2024
1 parent 6587754 commit a29d9eb
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 12 deletions.
35 changes: 29 additions & 6 deletions app/models/oauth2_token.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,37 @@
package models

import (
"database/sql/driver"
"encoding/json"
"errors"
)

type Oauth2Token struct {
UserID string `json:"user_id"`
TokenType string `json:"token_type"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
RefreshExpiresIn int `json:"refresh_expires_in"`
UserID string `json:"user_id"`
TokenType string `json:"token_type"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
RefreshExpiresIn int `json:"refresh_expires_in"`
Permissions StrArray `json:"permissions" gorm:"type:jsonb;index,type:gin"`
}

func (Oauth2Token) TableName() string {
return "oauth2_tokens"
}

type StrArray []string

// Value Marshal
func (a StrArray) Value() (driver.Value, error) {
return json.Marshal(a)
}

// Scan Unmarshal
func (a *StrArray) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
return errors.New("type assertion to []byte failed")
}
return json.Unmarshal(b, &a)
}
10 changes: 4 additions & 6 deletions internal/auth/keycloak.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,19 +47,17 @@ func RefreshTokenIfNecessary(user_id string) error {
keycloak.Ctx = context.Background()
}

rptResult, err := keycloak.Client.RetrospectToken(
result, _, err := keycloak.Client.DecodeAccessToken(
keycloak.Ctx,
token.RefreshToken,
helpers.Env("KEYCLOAK_CLIENT_ID", ""),
helpers.Env("KEYCLOAK_CLIENT_SECRET", ""),
token.AccessToken,
helpers.Env("KEYCLOAK_REALM", ""),
)

if err != nil {
return errors.New("an error occured while retrospecting token")
return errors.New("an error occured while validating token")
}

if !*rptResult.Active {
if !result.Valid {
err := RefreshToken(token)
if err != nil {
return err
Expand Down
9 changes: 9 additions & 0 deletions internal/liman/role_system.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ func GetPermissions(user *models.User, extFilter string) ([]string, map[string]s
variables = helpers.MergeStringMaps(variables, variable)
}

if user.AuthType == "keycloak" {
token := &models.Oauth2Token{}
database.Connection().First(&token, "user_id = ?", user.ID)

if token.UserID != "" {
permissions = append(permissions, token.Permissions...)
}
}

return permissions, variables, nil
}

Expand Down

0 comments on commit a29d9eb

Please sign in to comment.