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

fix pipeline, refactor away some boilerplate in the handlers #298

Merged
merged 4 commits into from
Jul 8, 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
40 changes: 28 additions & 12 deletions .github/workflows/container_builds.yml
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
name: Container ECR builds
name: Container ECR build + deploy
on:
push:
branches:
- main
paths:
- "frontend/**"
- "backend/**"
- "provider-middleware/*"

permissions:
id-token: write
contents: read

jobs:
setup-env:
if: github.repository == 'UnlockedLabs/UnlockEdv2' || github.repository == 'PThorpe92/UnlockEdv2'
runs-on: ubuntu-latest
outputs:
frontend_changes: ${{ steps.frontend_changes.outputs.changed }}
Expand Down Expand Up @@ -43,15 +40,20 @@ jobs:
echo "Middleware changes: ${{ steps.middleware_changes.outputs.changed }}"

build-and-push:
if: github.repository == 'UnlockedLabs/UnlockEdv2' || github.repository == 'PThorpe92/UnlockEdv2'
needs: setup-env
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/GithubActionsRole
role-to-assume: ${{ secrets.AWS_IAM_ROLE }}
aws-region: us-west-2
mask-aws-account-id: true

- name: Log in to Amazon ECR
id: login-ecr
Expand All @@ -63,17 +65,31 @@ jobs:
- name: Build and push frontend image
if: ${{ needs.setup-env.outputs.frontend_changes != '0' }}
run: |
docker buildx build --platform linux/amd64 -t ${{ steps.login-ecr.outputs.registry }}/frontend:latest -f frontend/Dockerfile .
docker push ${{ steps.login-ecr.outputs.registry }}/frontend:latest
docker buildx build --platform linux/amd64 -t=${{ steps.login-ecr.outputs.registry }}/frontend:latest --push frontend/.

- name: Build and push backend image
if: ${{ needs.setup-env.outputs.backend_changes != '0' }}
run: |
docker buildx build --platform linux/amd64 -t ${{ steps.login-ecr.outputs.registry }}/unlockedv2:latest -f backend/Dockerfile .
docker push ${{ steps.login-ecr.outputs.registry }}/unlockedv2:latest
docker buildx build --platform linux/amd64 -t=${{ steps.login-ecr.outputs.registry }}/unlockedv2:latest --push -f backend/Dockerfile .

- name: Build and push middleware image
if: ${{ needs.setup-env.outputs.middleware_changes != '0' }}
run: |
docker buildx build --platform linux/amd64 -t ${{ steps.login-ecr.outputs.registry }}/provider_middleware:latest -f provider-middleware/Dockerfile .
docker push ${{ steps.login-ecr.outputs.registry }}/provider_middleware:latest
docker buildx build --platform linux/amd64 -t=${{ steps.login-ecr.outputs.registry }}/provider_middleware:latest --push -f provider-middleware/Dockerfile .

deploy-to-staging:
if: github.repository == 'UnlockedLabs/UnlockEdv2' || github.repository == 'PThorpe92/UnlockEdv2'

needs: build-and-push
runs-on: ubuntu-latest
steps:
- name: Set up kubectl
uses: azure/setup-kubectl@v1
with:
version: v1.21.0

- name: Set up Kubeconfig
run: |
mkdir -p $HOME/.kube && touch $HOME/.kube/config
echo "${{ secrets.KUBECTL_CONFIG }}" | base64 -d > $HOME/.kube/config
kubectl rollout restart deployment
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
.github/workflows/test.yml
/frontend/.husky/staged-files
jar
/config/logs
/logs/*.log
/logs/*.json
/frontend/public/build
Expand Down
2 changes: 1 addition & 1 deletion backend/src/database/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (db *DB) AssignTempPasswordToUser(id uint) (string, error) {
if err != nil {
return "", err
}
if user.Role == "admin" {
if user.Role == models.Admin {
return "", errors.New("user not found, or user is admin and cannot have password reset")
}
psw := user.CreateTempPassword()
Expand Down
24 changes: 4 additions & 20 deletions backend/src/handlers/actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,7 @@ func (srv *Server) HandleGetUsers(w http.ResponseWriter, r *http.Request) {
Message: "Successfully fetched users from provider",
Meta: models.NewPaginationInfo(page, perPage, int64(total)),
}
if err := srv.WriteResponse(w, http.StatusOK, response); err != nil {
log.Error("Error writing response:" + err.Error())
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
srv.WriteResponse(w, http.StatusOK, response)
return
} else {
delete(cachedProviderUsers, uint(service.ProviderPlatformID))
Expand All @@ -159,12 +155,7 @@ func (srv *Server) HandleGetUsers(w http.ResponseWriter, r *http.Request) {
total, responseUsers := paginateUsers(externalUsers, page, perPage)
cachedProviderUsers[uint(service.ProviderPlatformID)] = CachedProviderUsers{Users: externalUsers, LastUpdated: time.Now()}
response := models.PaginatedResource[models.ImportUser]{Data: responseUsers, Message: "Successfully fetched users from provider", Meta: models.NewPaginationInfo(page, perPage, int64(total))}
if err := srv.WriteResponse(w, http.StatusOK, response); err != nil {
log.Error("Error writing response:" + err.Error())
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
delete(cachedProviderUsers, uint(service.ProviderPlatformID))
return
}
srv.WriteResponse(w, http.StatusOK, response)
}

func (srv *Server) HandleImportPrograms(w http.ResponseWriter, r *http.Request) {
Expand All @@ -180,11 +171,7 @@ func (srv *Server) HandleImportPrograms(w http.ResponseWriter, r *http.Request)
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
if err := srv.WriteResponse(w, http.StatusOK, models.Resource[interface{}]{Message: "Successfully imported courses"}); err != nil {
log.Error("Error writing response:" + err.Error())
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
srv.WriteResponse(w, http.StatusOK, models.Resource[interface{}]{Message: "Successfully imported courses"})
}

func (srv *Server) HandleImportMilestones(w http.ResponseWriter, r *http.Request) {
Expand All @@ -210,10 +197,7 @@ func (srv *Server) HandleImportMilestones(w http.ResponseWriter, r *http.Request
}
}
}
if err := srv.WriteResponse(w, http.StatusOK, models.Resource[interface{}]{Message: "Successfully imported Milestones"}); err != nil {
log.Error("Failed to write response")
srv.ErrorResponse(w, http.StatusInternalServerError, "error writing response")
}
srv.WriteResponse(w, http.StatusOK, models.Resource[interface{}]{Message: "Successfully imported Milestones"})
}

func (srv *Server) getProgramsAndMappingsForProvider(providerID uint) ([]models.Program, []models.ProviderUserMapping, error) {
Expand Down
31 changes: 8 additions & 23 deletions backend/src/handlers/activity_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import (
"net/http"
"strconv"
"time"

log "github.com/sirupsen/logrus"
)

func (srv *Server) registerActivityRoutes() {
Expand Down Expand Up @@ -38,19 +36,16 @@ func (srv *Server) HandleGetActivityByUserID(w http.ResponseWriter, r *http.Requ
srv.ErrorResponse(w, http.StatusInternalServerError, "Failed to get activities")
return
}
if err = srv.WriteResponse(w, http.StatusOK, map[string]interface{}{
srv.WriteResponse(w, http.StatusOK, map[string]interface{}{
"activities": activities,
}); err != nil {
srv.ErrorResponse(w, http.StatusInternalServerError, "Failed to write response")
log.Error("Failed to write response", err)
}
})
}

/****
* @Query Params:
* ?year=: year (default last year)
****/
func (srv *Server) HandleGetDailyActivityByUserID(w http.ResponseWriter, r *http.Request) {
func (srv *Server) HandleGetDailyActivityByUserID(w http.ResponseWriter, r *http.Request) {
// Parse userID from path
userID, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
Expand Down Expand Up @@ -79,15 +74,11 @@ func (srv *Server) HandleGetActivityByUserID(w http.ResponseWriter, r *http.Requ
}

// Write response
if err = srv.WriteResponse(w, http.StatusOK, map[string]interface{}{
srv.WriteResponse(w, http.StatusOK, map[string]interface{}{
"activities": activities,
}); err != nil {
srv.ErrorResponse(w, http.StatusInternalServerError, "Failed to write response")
log.Error("Failed to write response", err)
}
})
}


func (srv *Server) HandleGetProgramActivity(w http.ResponseWriter, r *http.Request) {
programID, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
Expand All @@ -100,13 +91,10 @@ func (srv *Server) HandleGetProgramActivity(w http.ResponseWriter, r *http.Reque
srv.ErrorResponse(w, http.StatusInternalServerError, "Failed to get activities")
return
}
if err = srv.WriteResponse(w, http.StatusOK, map[string]interface{}{
srv.WriteResponse(w, http.StatusOK, map[string]interface{}{
"count": count,
"activities": activities,
}); err != nil {
srv.ErrorResponse(w, http.StatusInternalServerError, "Failed to write response")
log.Error("Failed to write response", err)
}
})
}

func (srv *Server) HandleCreateActivity(w http.ResponseWriter, r *http.Request) {
Expand All @@ -119,8 +107,5 @@ func (srv *Server) HandleCreateActivity(w http.ResponseWriter, r *http.Request)
srv.ErrorResponse(w, http.StatusInternalServerError, "Failed to create activity")
return
}
if err := srv.WriteResponse(w, http.StatusOK, activity); err != nil {
srv.ErrorResponse(w, http.StatusInternalServerError, "Failed to write response")
log.Error("Failed to write response", err)
}
srv.WriteResponse(w, http.StatusOK, activity)
}
18 changes: 3 additions & 15 deletions backend/src/handlers/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,11 +167,7 @@ func (srv *Server) handleCheckAuth(w http.ResponseWriter, r *http.Request) {
if orySession, ok := orySessions[user.ID]; ok {
// check the cached session hash + expiration
if orySession.Active && orySession.TokenHash == cookieHash && orySession.Expires.After(time.Now()) {
if err := srv.WriteResponse(w, http.StatusOK, user); err != nil {
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
log.Error("Error writing response: " + err.Error())
return
}
srv.WriteResponse(w, http.StatusOK, user)
log.WithFields(fields).Info("checked cached session active for user")
return
}
Expand All @@ -182,11 +178,7 @@ func (srv *Server) handleCheckAuth(w http.ResponseWriter, r *http.Request) {
srv.ErrorResponse(w, http.StatusUnauthorized, "ory session was not valid, please login again")
return
}
if err := srv.WriteResponse(w, http.StatusOK, user); err != nil {
log.Error("Error writing response: " + err.Error())
srv.ErrorResponse(w, http.StatusUnauthorized, "unauthorized, ory session not found")
return
}
srv.WriteResponse(w, http.StatusOK, user)
return
}
http.Error(w, "Unauthorized", http.StatusUnauthorized)
Expand Down Expand Up @@ -298,11 +290,7 @@ func (srv *Server) handleResetPassword(w http.ResponseWriter, r *http.Request) {
return
}
}
if err = srv.WriteResponse(w, http.StatusOK, "Password reset successfully"); err != nil {
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
log.Error("Error writing response: " + err.Error())
return
}
srv.WriteResponse(w, http.StatusOK, "Password reset successfully")
}

func validatePassword(pass string) bool {
Expand Down
35 changes: 12 additions & 23 deletions backend/src/handlers/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,38 +15,35 @@ func (srv *Server) registerDashboardRoutes() {
}

func (srv *Server) HandleStudentDashboard(w http.ResponseWriter, r *http.Request) {
fields := log.Fields{"handler": "HandleStudentDashboard"}
userId, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
log.Errorf("Error parsing user ID: %v", err)
fields["error"] = err.Error()
log.WithFields(fields).Errorf("Error parsing user ID: %v", err)
srv.ErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
studentDashboard, err := srv.Db.GetStudentDashboardInfo(userId)
if err != nil {
log.Errorf("Error getting user dashboard info: %v", err)
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
if err := srv.WriteResponse(w, http.StatusOK, studentDashboard); err != nil {
log.Errorf("user dashboard endpoint: error writing response: %v", err)
fields["error"] = err.Error()
log.WithFields(fields).Errorf("Error getting user dashboard info: %v", err)
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
srv.WriteResponse(w, http.StatusOK, studentDashboard)
}

func (srv *Server) HandleAdminDashboard(w http.ResponseWriter, r *http.Request) {
fields := log.Fields{"handler": "HandleAdminDashboard"}
claims := r.Context().Value(ClaimsKey).(*Claims)
adminDashboard, err := srv.Db.GetAdminDashboardInfo(claims.FacilityID)
if err != nil {
log.Errorf("Error getting user dashboard info: %v", err)
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
if err := srv.WriteResponse(w, http.StatusOK, adminDashboard); err != nil {
log.Errorf("user dashboard endpoint: error writing response: %v", err)
fields["error"] = err.Error()
log.WithFields(fields).Errorf("Error getting user dashboard info: %v", err)
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
srv.WriteResponse(w, http.StatusOK, adminDashboard)
}

/**
Expand All @@ -70,11 +67,7 @@ func (srv *Server) HandleUserCatalogue(w http.ResponseWriter, r *http.Request) {
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
if err := srv.WriteResponse(w, http.StatusOK, userCatalogue); err != nil {
log.Errorf("user catalogue endpoint: error writing response: %v", err)
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
srv.WriteResponse(w, http.StatusOK, userCatalogue)
}

func (srv *Server) HandleUserPrograms(w http.ResponseWriter, r *http.Request) {
Expand All @@ -100,9 +93,5 @@ func (srv *Server) HandleUserPrograms(w http.ResponseWriter, r *http.Request) {
"num_completed": numCompleted,
"total_time": totalTime,
}
if err := srv.WriteResponse(w, http.StatusOK, response); err != nil {
log.Errorf("user programs endpoint: error writing response: %v", err)
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
srv.WriteResponse(w, http.StatusOK, response)
}
22 changes: 4 additions & 18 deletions backend/src/handlers/facilities_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,7 @@ func (srv *Server) HandleIndexFacilities(w http.ResponseWriter, r *http.Request)
Message: "facilities fetched successfully",
Data: facilities,
}
if err = srv.WriteResponse(w, http.StatusOK, response); err != nil {
log.WithFields(fields).Error("error writing response")
http.Error(w, err.Error(), http.StatusInternalServerError)
}
srv.WriteResponse(w, http.StatusOK, response)
}

func (srv *Server) HandleShowFacility(w http.ResponseWriter, r *http.Request) {
Expand All @@ -56,10 +53,7 @@ func (srv *Server) HandleShowFacility(w http.ResponseWriter, r *http.Request) {
Data: make([]models.Facility, 0),
}
response.Data = append(response.Data, *facility)
if err = srv.WriteResponse(w, http.StatusOK, response); err != nil {
log.WithFields(fields).Error("error writing response")
http.Error(w, err.Error(), http.StatusInternalServerError)
}
srv.WriteResponse(w, http.StatusOK, response)
}

func (srv *Server) HandleCreateFacility(w http.ResponseWriter, r *http.Request) {
Expand All @@ -84,11 +78,7 @@ func (srv *Server) HandleCreateFacility(w http.ResponseWriter, r *http.Request)
Data: []models.Facility{*newFacility},
Message: "Facility created successfully",
}
if err = srv.WriteResponse(w, http.StatusOK, response); err != nil {
fields["error"] = err
log.Error("Error writing response")
srv.ErrorResponse(w, http.StatusInternalServerError, err.Error())
}
srv.WriteResponse(w, http.StatusOK, response)
}

func (srv *Server) HandleUpdateFacility(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -121,11 +111,7 @@ func (srv *Server) HandleUpdateFacility(w http.ResponseWriter, r *http.Request)
Data: []models.Facility{*toReturn},
Message: "facility successfully updated",
}
if err = srv.WriteResponse(w, http.StatusOK, response); err != nil {
fields["error"] = err
log.WithFields(fields).Error("error writing response")
http.Error(w, err.Error(), http.StatusInternalServerError)
}
srv.WriteResponse(w, http.StatusOK, response)
}

func (srv *Server) HandleDeleteFacility(w http.ResponseWriter, r *http.Request) {
Expand Down
Loading
Loading