Skip to content

Commit

Permalink
feat: add ory keto, refactoring, oidc work
Browse files Browse the repository at this point in the history
  • Loading branch information
PThorpe92 committed May 31, 2024
1 parent 125b976 commit f916084
Show file tree
Hide file tree
Showing 10 changed files with 89 additions and 33 deletions.
37 changes: 20 additions & 17 deletions backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
)

func main() {
file := os.Stdout
defer file.Close()
if err := godotenv.Load(); err != nil {
log.Info("no .env file found, using default env variables")
}
Expand All @@ -22,7 +24,7 @@ func main() {
port = "8080"
}
testing := (env == "testing")
initLogging(env)
initLogging(env, file)
newServer := server.NewServer(testing)
log.Info("Starting server on :", port)
fmt.Println("Starting server on :", port)
Expand All @@ -31,33 +33,34 @@ func main() {
}
}

func initLogging(env string) {
var file *os.File
func initLogging(env string, file *os.File) {
var err error
prod := (env == "prod" || env == "production")
logLevel := os.Getenv("LOG_LEVEL")
if prod {
file, err = os.OpenFile("logs/server.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("Failed to open log file: %v", err)
}
if logLevel == "" {
logLevel = "info"
}
log.SetFormatter(&log.JSONFormatter{})
} else {
if logLevel == "" {
logLevel = "debug"
}
file = os.Stdout
log.SetFormatter(&log.TextFormatter{ForceColors: true})
}
defer file.Close()
level, err := log.ParseLevel(logLevel)
if err != nil {
log.Errorf("Error parsing log level: %v", err)
level = log.InfoLevel
}
level := parseLogLevel()
log.SetLevel(level)
log.SetOutput(file)
}

func parseLogLevel() log.Level {
level := os.Getenv("LOG_LEVEL")
switch level {
case "":
return log.InfoLevel
default:
level, err := log.ParseLevel(level)
if err != nil {
log.Errorf("Error parsing log level: %v", err)
level = log.InfoLevel
}
return level
}
}
13 changes: 11 additions & 2 deletions backend/src/handlers/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,17 +217,26 @@ func (srv *Server) handleConsent(w http.ResponseWriter, r *http.Request) {
return
}
redirectURI := consentResponse["redirect_to"].(string)
http.Redirect(w, r.WithContext(r.Context()), redirectURI, http.StatusSeeOther)
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:4444")
http.Redirect(w, r, redirectURI, http.StatusFound)
}

func (s *Server) handleOidcLogin(w http.ResponseWriter, r *http.Request, claims Claims, challenge string) {
log.Info("login challenge initiated", challenge)
client := &http.Client{}
body := map[string]interface{}{}
body["subject"] = claims.Subject
sub, err := claims.GetSubject()
if err != nil {
// by this point, the user cannot be nil
log.Debugf("Error getting subject from claims, using username %v", err)
user := s.Db.GetUserByID(claims.UserID)
sub = user.Username
}
body["subject"] = sub
body["remember"] = true
body["remember_for"] = 3600
loginChallenge := "?login_challenge=" + challenge
log.Debug("sending login request to hydr: ", body)
jsonBody, err := json.Marshal(body)
if err != nil {
log.Error("Error marshalling body")
Expand Down
4 changes: 2 additions & 2 deletions backend/src/handlers/oidc.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ type RegisterClientRequest struct {
func (srv *Server) HandleRegisterClient(w http.ResponseWriter, r *http.Request) {
request := RegisterClientRequest{}
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
log.Error(r, err)
log.Error("error decoding body: register oidc client", err)
srv.ErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
provider, err := srv.Db.GetProviderPlatformByID(int(request.ProviderPlatformID))
if err != nil {
log.Error("no provider platform found with that ID", err)
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
log.Error(r, err)
return
}
if provider.OidcID != 0 || provider.ExternalAuthProviderId != "" {
Expand Down
4 changes: 3 additions & 1 deletion backend/src/models/oidc_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,14 @@ func OidcClientFromProvider(prov *ProviderPlatform, autoRegister bool) (*OidcCli
headers["Origin"] = os.Getenv("APP_URL")
body := map[string]interface{}{}
body["client_name"] = prov.Name
body["client_uri"] = prov.BaseUrl
body["redirect_uris"] = []string{redirectURI}
body["scopes"] = DefaultScopes
body["acces_token_strategy"] = "opaque"
body["metadata"] = map[string]interface{}{
"Origin": os.Getenv("APP_URL"),
}
body["subject_type"] = "username"
body["allowed_cors_origins"] = []string{os.Getenv("HYDRA_ADMIN_URL"), os.Getenv("APP_URL"), prov.BaseUrl, os.Getenv("HYDRA_PUBLIC_URL")}
body["grant_types"] = []string{"authorization_code"}
body["authorization_code_grant_access_token_lifespan"] = "3h"
Expand All @@ -75,7 +77,7 @@ func OidcClientFromProvider(prov *ProviderPlatform, autoRegister bool) (*OidcCli
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
return nil, externalId, fmt.Errorf("error creating client: %s", resp.Status)
return nil, externalId, fmt.Errorf("error creating client in hydra oidc server: received %s", resp.Status)
}
var clientData map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&clientData)
Expand Down
4 changes: 2 additions & 2 deletions config/docker-compose.fe-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ services:
command: >
./backend
volumes:
- ./logs:/logs/
- logs:/logs/
networks:
- intranet

Expand All @@ -37,7 +37,7 @@ services:
networks:
- intranet
volumes:
- ./logs:/logs
- logs:/logs
depends_on:
postgres:
condition: service_healthy
7 changes: 4 additions & 3 deletions config/docker-compose.prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ services:
- DB_USER=unlocked
- DB_PASSWORD=dev
- DB_NAME=unlocked
- APP_URL=http://localhost
- PROVIDER_SERVICE_URL=http://provider-service:8081
- HYDRA_ADMIN_URL=http://hydra:4445
- HYDRA_PUBLIC_URL=http://hydra:4444
Expand All @@ -23,7 +24,7 @@ services:
command: >
./backend
volumes:
- ./logs:/logs/
- logs:/logs/
networks:
- intranet

Expand All @@ -37,7 +38,7 @@ services:
networks:
- intranet
volumes:
- ./logs:/logs
- logs:/logs
depends_on:
postgres:
condition: service_healthy
Expand All @@ -56,5 +57,5 @@ services:
- intranet
volumes:
- ./config/nginx.conf:/etc/nginx/conf.d/default.conf
- ./logs:/var/log/nginx/
- logs:/var/log/nginx/
depends_on: [server]
18 changes: 18 additions & 0 deletions config/keto.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
version: v0.8.0-alpha.2

log:
level: debug

namespaces:
- id: 0
name: videos

serve:
read:
host: 0.0.0.0
port: 4466
write:
host: 0.0.0.0
port: 4467

dsn: memory
2 changes: 1 addition & 1 deletion config/nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ server {
proxy_cache_bypass $http_upgrade;
}

location /admin/oauth2 {
location /admin {
proxy_pass http://hydra:4445;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
Expand Down
25 changes: 24 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ services:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
- ./logs:/var/log/postgresql
- logs:/var/log/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U unlocked"]
interval: 10s
Expand All @@ -18,6 +18,18 @@ services:
networks:
- intranet

keto:
image: oryd/keto:v0.12.0-alpha.0
ports:
- "4466:4466"
- "4467:4467"
command: serve -c /home/ory/keto.yml
restart: on-failure
volumes:
- type: bind
source: config/keto.yml
target: /home/ory/keto.yml

hydra:
image: oryd/hydra:v2.2.0
ports:
Expand All @@ -34,6 +46,10 @@ services:
source: ./hydra
target: /etc/config/hydra
environment:
- SERVE_PUBLIC_CORS_ENABLED=true
- SERVE_PUBLIC_CORS_ALLOWED_METHODS=POST,GET,PUT,DELETE
- SERVE_ADMIN_CORS_ENABLED=true
- SERVE_ADMIN_CORS_ALLOWED_METHODS=POST,GET,PUT,DELETE
- DSN=sqlite:///var/lib/sqlite/db.sqlite?_fk=true
restart: unless-stopped
env_file: ./backend/.env
Expand Down Expand Up @@ -62,4 +78,11 @@ networks:

volumes:
postgres_data:
logs:
driver: local
driver_opts:
type: none
o: bind
device: ./logs

hydra-sqlite:
8 changes: 4 additions & 4 deletions hydra/hydra.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ serve:
- http://localhost:8080
- http://localhost:5173
- http://localhost
- https://staging.canavs.unlockedlabs.xyz
- https://staging.canvas.unlockedlabs.xyz
allowed_methods:
- POST
- GET
Expand All @@ -23,9 +23,9 @@ serve:
cors:
enabled: true
allowed_origins:
- http://localhost:8080
- http://localhost:5173
- http://localhost
- https://staging.canvas.unlockedlabs.xyz
- http://localhost/login
allowed_methods:
- POST
- GET
Expand All @@ -43,7 +43,7 @@ log:

urls:
self:
issuer: http://localhost:4444
issuer: http://localhost
consent: http://localhost/consent
login: http://localhost/login
logout: http://localhost/logout
Expand Down

0 comments on commit f916084

Please sign in to comment.