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

Ory integration + setup, some endpoints for the UI #256

Merged
merged 11 commits into from
Jun 13, 2024
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
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ DB_NAME=unlocked
APP_URL=http://localhost:8080
PUBLIC_DIR=./frontend/public
APP_ENV=dev
LOG_LEVEL=debug

HYDRA_ADMIN_URL=http://localhost:4445
HYDRA_PUBLIC_URL=http://localhost:4444
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
.github/workflows/test.yml
/frontend/.husky/staged-files
jar
/logs/*.log
/logs/*
/frontend/public/build
/frontend/public/thumbnails/*
/migrations/migrations
Expand Down
2 changes: 1 addition & 1 deletion backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ require (
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/jackc/pgx v3.6.2+incompatible
github.com/joho/godotenv v1.5.1
github.com/ory/kratos-client-go v1.2.0
github.com/sirupsen/logrus v1.9.3
golang.org/x/crypto v0.22.0
gorm.io/datatypes v1.2.0
Expand All @@ -29,7 +30,6 @@ require (
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/stretchr/testify v1.9.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/microsoft/go-mssqldb v0.17.0 h1:Fto83dMZPnYv1Zwx5vHHxpNraeEaUlQ/hhHLgZiaenE=
github.com/microsoft/go-mssqldb v0.17.0/go.mod h1:OkoNGhGEs8EZqchVTtochlXruEhEOaO4S0d2sB5aeGQ=
github.com/ory/kratos-client-go v1.2.0 h1:uB9EbeNuYFJbE36Jjx3V7d1piNk15eTCBB8fE/UD+us=
github.com/ory/kratos-client-go v1.2.0/go.mod h1:WiQYlrqW4Atj6Js7oDN5ArbZxo0nTO2u/e1XaDv2yMI=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
Expand Down
40 changes: 30 additions & 10 deletions backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,28 @@ 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")
}
var file *os.File
var err error
env := os.Getenv("APP_ENV")
port := os.Getenv("APP_PORT")
if port == "" {
port = "8080"
}
env := os.Getenv("APP_ENV")
testing := (env == "testing")
initLogging(env, file)
newServer := server.NewServer(testing)
log.Info("Starting server on :", port)
fmt.Println("Starting server on :", port)
if err := http.ListenAndServe(":8080", server.CorsMiddleware(newServer.Mux)); err != nil {
log.Fatalf("Error starting server: %v", err)
}
}

func initLogging(env string, file *os.File) {
var err error
prod := (env == "prod" || env == "production")
if prod {
file, err = os.OpenFile("logs/server.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
Expand All @@ -32,15 +43,24 @@ func main() {
}
log.SetFormatter(&log.JSONFormatter{})
} else {
file = os.Stdout
log.SetFormatter(&log.TextFormatter{ForceColors: true})
}
defer file.Close()
level := parseLogLevel()
log.SetLevel(level)
log.SetOutput(file)
newServer := server.NewServer(testing)
log.Info("Starting server on :", port)
fmt.Println("Starting server on :", port)
if err := http.ListenAndServe(":8080", server.CorsMiddleware(newServer.Mux)); err != nil {
log.Fatalf("Error starting server: %v", err)
}

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
}
}
3 changes: 2 additions & 1 deletion backend/src/database/DB.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import (
"UnlockEdv2/src/models"
"encoding/json"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"time"

log "github.com/sirupsen/logrus"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
Expand Down Expand Up @@ -77,6 +77,7 @@ func SeedDefaultData(db *gorm.DB) {
Password: "ChangeMe!",
}
log.Printf("Creating user: %v", user)
log.Println("Make sure to sync the Kratos instance if you are freshly migrating")
err := user.HashPassword()
if err != nil {
log.Fatalf("Failed to hash password: %v", err)
Expand Down
32 changes: 0 additions & 32 deletions backend/src/database/leftmenulinks.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,35 +27,3 @@ func (db *DB) CreateFreshLeftMenuLinks(links []models.LeftMenuLink) error {
log.Infof("Left-Menu-Links created")
return nil
}

type UserCatalogueJoin struct {
ProgramID uint `json:"program_id"`
ThumbnailURL string `json:"thumbnail_url"`
ProgramName string `json:"program_name"`
ProviderName string `json:"provider_name"`
ExternalURL string `json:"external_url"`
ProgramType string `json:"program_type"`
IsFavorited bool `json:"is_favorited"`
OutcomeTypes string `json:"outcome_types"`
}

func (db *DB) GetUserCatalogue(userId int, tags []string) ([]UserCatalogueJoin, error) {
catalogue := []UserCatalogueJoin{}
tx := db.Conn.Table("programs p").
Select("p.id as program_id, p.thumbnail_url, p.name as program_name, pp.name as provider_name, p.external_url, p.type as program_type, p.outcome_types, f.user_id IS NOT NULL as is_favorited").
Joins("LEFT JOIN provider_platforms pp ON p.provider_platform_id = pp.id").
Joins("LEFT JOIN favorites f ON f.program_id = p.id AND f.user_id = ?", userId)
for i, tag := range tags {
if i == 0 {
tx.Where("p.outcome_types ILIKE ?", "%"+tag+"%")
} else {
tx.Or("p.outcome_types ILIKE ?", "%"+tag+"%")
}
tx.Or("p.type ILIKE ?", "%"+tag+"%")
}
err := tx.Scan(&catalogue).Error
if err != nil {
return nil, err
}
return catalogue, nil
}
22 changes: 16 additions & 6 deletions backend/src/database/milestones.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ func (db *DB) GetMilestones(page, perPage int, search, orderBy string) (int64, [
content []MilestoneResponse
total int64
)

query := db.Conn.Model(&models.Milestone{}).Select("milestones.*, provider_platforms.name as provider_platform_name, programs.name as program_name, users.username").
Joins("JOIN programs ON milestones.program_id = programs.id").
Joins("JOIN provider_platforms ON programs.provider_platform_id = provider_platforms.id").
Expand All @@ -70,12 +69,23 @@ func (db *DB) GetMilestones(page, perPage int, search, orderBy string) (int64, [
return total, content, nil
}

func (db *DB) GetMilestonesByProviderPlatformID(id int) ([]models.Milestone, error) {
content := []models.Milestone{}
if err := db.Conn.Where("provider_platform_id = ?", id).Find(&content).Error; err != nil {
return nil, err
func (db *DB) GetMilestonesForUser(page, perPage int, id uint) (int64, []MilestoneResponse, error) {
content := []MilestoneResponse{}
total := int64(0)
err := db.Conn.Model(&models.Milestone{}).Select("milestones.*, provider_platforms.name as provider_platform_name, programs.name as program_name, users.username").
Joins("JOIN programs ON milestones.program_id = programs.id").
Joins("JOIN provider_platforms ON programs.provider_platform_id = provider_platforms.id").
Joins("JOIN users ON milestones.user_id = users.id").
Where("user_id = ?", id).
Count(&total).
Limit(perPage).
Offset((page - 1) * perPage).
Find(&content).
Error
if err != nil {
return 0, nil, err
}
return content, nil
return total, content, nil
}

func (db *DB) CreateMilestone(content *models.Milestone) (*models.Milestone, error) {
Expand Down
80 changes: 80 additions & 0 deletions backend/src/database/user_catalogue.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package database

type UserCatalogueJoin struct {
ProgramID uint `json:"program_id"`
ThumbnailURL string `json:"thumbnail_url"`
ProgramName string `json:"program_name"`
ProviderName string `json:"provider_name"`
ExternalURL string `json:"external_url"`
ProgramType string `json:"program_type"`
IsFavorited bool `json:"is_favorited"`
OutcomeTypes string `json:"outcome_types"`
}

func (db *DB) GetUserCatalogue(userId int, tags []string) ([]UserCatalogueJoin, error) {
catalogue := []UserCatalogueJoin{}
tx := db.Conn.Table("programs p").
Select("p.id as program_id, p.thumbnail_url, p.name as program_name, pp.name as provider_name, p.external_url, p.type as program_type, p.outcome_types, f.user_id IS NOT NULL as is_favorited").
Joins("LEFT JOIN provider_platforms pp ON p.provider_platform_id = pp.id").
Joins("LEFT JOIN favorites f ON f.program_id = p.id AND f.user_id = ?", userId).
Where("p.deleted_at IS NULL").
Where("pp.deleted_at IS NULL")
for i, tag := range tags {
if i == 0 {
tx.Where("p.outcome_types ILIKE ?", "%"+tag+"%")
} else {
tx.Or("p.outcome_types ILIKE ?", "%"+tag+"%")
}
tx.Or("p.type ILIKE ?", "%"+tag+"%")
}
err := tx.Scan(&catalogue).Error
if err != nil {
return nil, err
}
return catalogue, nil
}

type UserPrograms struct {
ThumbnailURL string `json:"thumbnail_url"`
ProgramName string `json:"program_name"`
ProviderName string `json:"provider_name"`
ExternalURL string `json:"external_url"`
CourseProgress float64 `json:"course_progress"`
IsFavorited bool `json:"is_favorited"`
}

func (db *DB) GetUserPrograms(userId uint, tags []string) ([]UserPrograms, error) {
programs := []UserPrograms{}
tx := db.Conn.Table("programs p").
Select(`p.thumbnail_url,
p.name as program_name, pp.name as provider_name, p.external_url,
f.user_id IS NOT NULL as is_favorited,
COUNT(milestones.id) * 100.0 / p.total_progress_milestones as course_progress`).
Joins("LEFT JOIN provider_platforms pp ON p.provider_platform_id = pp.id").
Joins("LEFT JOIN milestones on milestones.program_id = p.id AND milestones.user_id = ?", userId).
Joins("LEFT JOIN favorites f ON f.program_id = p.id AND f.user_id = ?", userId).
Where("p.deleted_at IS NULL").
Where("pp.deleted_at IS NULL")
for i, tag := range tags {
var query string
switch tag {
case "is_favorited":
query = "is_favorited = true"
case "completed":
query = "milestones.is_completed = true"
case "in_progress":
query = "milestones.is_completed = false"
}
if i == 0 {
tx.Where(query)
} else {
tx.Or(query)
}
}
tx.Group("p.name, p.thumbnail_url, pp.name, p.external_url, f.user_id, p.total_progress_milestones")
err := tx.Scan(&programs).Error
if err != nil {
return nil, err
}
return programs, nil
}
4 changes: 2 additions & 2 deletions backend/src/database/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func (db *DB) GetCurrentUsers(page, itemsPerPage int) (int64, []models.User, err
return 0, nil, err
}

if err := db.Conn.Select("id", "email", "username", "name_first", "name_last", "role", "created_at", "updated_at", "password_reset").
if err := db.Conn.Select("id", "email", "username", "name_first", "name_last", "role", "created_at", "updated_at", "password_reset", "kratos_id").
Offset(offset).
Limit(itemsPerPage).
Find(&users).Error; err != nil {
Expand All @@ -30,7 +30,7 @@ func (db *DB) GetCurrentUsers(page, itemsPerPage int) (int64, []models.User, err

func (db *DB) GetUserByID(id uint) *models.User {
var user models.User
if err := db.Conn.Select("id", "email", "username", "name_first", "name_last", "role", "created_at", "updated_at", "password_reset").
if err := db.Conn.Select("id", "email", "username", "name_first", "name_last", "role", "created_at", "updated_at", "password_reset", "kratos_id").
Where("id = ?", id).
First(&user).Error; err != nil {
return nil
Expand Down
9 changes: 2 additions & 7 deletions backend/src/handlers/activity_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,12 @@ import (
)

func (srv *Server) registerActivityRoutes() {
srv.Mux.Handle("GET /api/users/{id}/activity", srv.applyMiddleware(http.HandlerFunc(srv.GetActivityByUserID)))
srv.Mux.Handle("GET /api/users/{id}/activity", srv.applyMiddleware(http.HandlerFunc(srv.HandleGetActivityByUserID)))
srv.Mux.Handle("GET /api/programs/{id}/activity", srv.applyAdminMiddleware(http.HandlerFunc(srv.HandleGetProgramActivity)))
srv.Mux.Handle("POST /api/users/{id}/activity", srv.applyAdminMiddleware(http.HandlerFunc(srv.HandleCreateActivity)))
}

/****
* @Query Params:
* ?program=: id
* ?year=: year (default last year)
****/
func (srv *Server) GetActivityByUserID(w http.ResponseWriter, r *http.Request) {
func (srv *Server) HandleGetActivityByUserID(w http.ResponseWriter, r *http.Request) {
userID, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
srv.ErrorResponse(w, http.StatusBadRequest, "Invalid user ID")
Expand Down
Loading
Loading