Skip to content

Commit

Permalink
Latest Code From Private Repo
Browse files Browse the repository at this point in the history
  • Loading branch information
AbdulDevHub committed Apr 4, 2024
1 parent a5fe45a commit d94fc6a
Show file tree
Hide file tree
Showing 13 changed files with 149 additions and 57 deletions.
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* @somegroupname/dev
13 changes: 13 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# What's Inside

- [ ] Placeholder 1
- [ ] Placeholder 2

... full details of acceptance criteria documented in the linked GitHub issue

[//]: <> 'Self Checklist When Opening a Pull Request'

[//]: # "Pull Request Title Follows <github issue number>: <Issue Title>, e.g. 123: Example Title (Commit messages do not need to follow convention but recommended)"
[//]: # "All ticket requirements are met. If not, then create a draft PR"
[//]: # "GitHub Issue Pre-Linked to Branch"
[//]: # "Correct Label to this Branch (Can be done after PR is created)"
44 changes: 44 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: Go

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
build:
runs-on: ubuntu-latest

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

- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: 1.21.6

- name: Build
run: go build

- name: Rename env
run: mv .env.example .env

- name: Run
run: |
go run . &
echo "Server started"
- name: Wait
run: sleep 3

- name: Test
run: |
cd tests
go test -v
- name: rename env
run: mv .env .env.example
1 change: 0 additions & 1 deletion api/page.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ type PageResp struct {
type PageUpdateRequest struct {
Page PageUpdateObject `json:"page"`
Elements []ElementsUpdateObject `json:"elements,omitempty"`
// RemoveElements []string `json:"remove_elements,omitempty"`
}

type PageUpdateObject struct {
Expand Down
10 changes: 8 additions & 2 deletions controllers/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
// Return "localhost" if the app is in development mode otherwise return the DOMAIN env variable.
func GetDomain() string {
if os.Getenv("APP_ENV") == "development" {
return "localhost"
return "http://localhost:8000"
}
return os.Getenv("DOMAIN")
}
Expand Down Expand Up @@ -234,7 +234,13 @@ func AuthenticateUser(c *gin.Context) (uint, error) {
}
// Attach new tokens to browser
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie("Authorization1", tokenString, expiry, "", GetFrontendURL(), os.Getenv("APP_ENV") != "development", true)

// Trim the protocol and port from the frontend URL
url := strings.TrimPrefix(GetFrontendURL(), "https://")
url = strings.TrimPrefix(url, "http://")
url = strings.Split(url, ":")[0]

c.SetCookie("Authorization", tokenString, expiry, "", url, os.Getenv("APP_ENV") != "development", true)
// Update in DB
newTokensMade = true
}
Expand Down
82 changes: 50 additions & 32 deletions controllers/page.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/opalescencelabs/backend/api"
"github.com/opalescencelabs/backend/api/caching"
"github.com/opalescencelabs/backend/controllers/auth"
"github.com/opalescencelabs/backend/controllers/templates"
"github.com/opalescencelabs/backend/database"
"github.com/opalescencelabs/backend/models"
"gorm.io/gorm"
Expand Down Expand Up @@ -440,8 +441,20 @@ func PageList(c *gin.Context) {

result := database.DB.Where("user_id = ? AND deleted_at IS NULL", userID).Order("is_favourite DESC, last_updated_at DESC").Find(&pages)
if result.Error != nil || len(pages) == 0 {
c.JSON(http.StatusNotFound, gin.H{"error": "No pages found for this user"})
return
// Generate welcome page if no pages are found
fmt.Println("No pages found for user ", userID)
fmt.Println("Creating welcome page")
// Begin a transaction for the creation of the welcome page
tx := database.DB.Begin()
if err := templates.CreateWelcomePage(userID, tx); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create welcome page. " + err.Error()})
return
}
// Commit the transaction
if err := tx.Commit().Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create welcome page. " + err.Error()})
return
}
}

// Convert pages to PageResp, including unmarshalling ElementPositions
Expand Down Expand Up @@ -578,6 +591,8 @@ func PageUpdate(c *gin.Context) {
return
}

// If elements is not present in the request, make no changes to the elements

PageID := page.ID

elementQuery := "element_uuid = ? AND page_id = ? AND user_id = ?"
Expand Down Expand Up @@ -620,39 +635,42 @@ func PageUpdate(c *gin.Context) {
}
}

// Iterate over the existing element positions and delete the ones that are not present in the newElementPositions slice
for _, existingElementUUID := range existingElementPositions {
if !slices.Contains(newElementPositions, existingElementUUID) {
// Delete the element
var element models.Element
if err := tx.Where("element_uuid = ? AND page_id = ? AND user_id = ?", existingElementUUID, PageID, userID).First(&element).Error; err != nil {
fmt.Println("Element not found:", existingElementUUID, err)
c.JSON(http.StatusBadRequest, gin.H{"error": "delete element that doesn't exist"})
tx.Rollback()
return
}
if err := tx.Delete(&element).Error; err != nil {
fmt.Println("Failed to delete elements", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "remove elements"})
tx.Rollback()
return
// If elements is nill (i.e. not present in the request), do nothing to the existing elements
if request.Elements != nil {
// Iterate over the existing element positions and delete the ones that are not present in the newElementPositions slice
for _, existingElementUUID := range existingElementPositions {
if !slices.Contains(newElementPositions, existingElementUUID) {
// Delete the element
var element models.Element
if err := tx.Where("element_uuid = ? AND page_id = ? AND user_id = ?", existingElementUUID, PageID, userID).First(&element).Error; err != nil {
fmt.Println("Element not found:", existingElementUUID, err)
c.JSON(http.StatusBadRequest, gin.H{"error": "delete element that doesn't exist"})
tx.Rollback()
return
}
if err := tx.Delete(&element).Error; err != nil {
fmt.Println("Failed to delete elements", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "remove elements"})
tx.Rollback()
return
}
}
}
}

// Marshal the newElementPositions slice and update the page's ElementPositions
newElementPositionsJSON, err := json.Marshal(newElementPositions)
if err != nil {
fmt.Println("Failed to marshal new element positions", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process page data (elementPositions)", "details": err.Error()})
tx.Rollback()
return
}
if err := tx.Model(&page).Update("element_positions", newElementPositionsJSON).Error; err != nil {
fmt.Println("Failed to update element positions", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "update element positions"})
tx.Rollback()
return
// Marshal the newElementPositions slice and update the page's ElementPositions
newElementPositionsJSON, err := json.Marshal(newElementPositions)
if err != nil {
fmt.Println("Failed to marshal new element positions", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process page data (elementPositions)", "details": err.Error()})
tx.Rollback()
return
}
if err := tx.Model(&page).Update("element_positions", newElementPositionsJSON).Error; err != nil {
fmt.Println("Failed to update element positions", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "update element positions"})
tx.Rollback()
return
}
}

// Commit the transaction
Expand Down
2 changes: 1 addition & 1 deletion controllers/templates/welcome/elements/a.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"user_id": 0,
"page_id": 0,
"element_uuid": "0",
"type": "Heading 1",
"type": "Heading 2",
"content": {
"text": "Welcome to Opalescence!"
},
Expand Down
2 changes: 1 addition & 1 deletion controllers/templates/welcome/elements/c.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"user_id": 0,
"page_id": 0,
"element_uuid": "0",
"type": "Heading 1",
"type": "Heading 3",
"content": {
"text": "To start off, try adding your name below:"
},
Expand Down
2 changes: 1 addition & 1 deletion controllers/templates/welcome/elements/e.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"user_id": 0,
"page_id": 0,
"element_uuid": "0",
"type": "Heading 1",
"type": "Heading 3",
"content": {
"text": "Now try changing the emoji on the callout:"
},
Expand Down
4 changes: 1 addition & 3 deletions controllers/templates/welcome/page.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,5 @@
"is_favourite": false,
"etc": null,
"view_count": 0,
"date_view_count": {
"2000-01-01" : 0
}
"date_view_count": {}
}
19 changes: 16 additions & 3 deletions controllers/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"os"
"strings"

"github.com/gin-gonic/gin"
"github.com/opalescencelabs/backend/api"
Expand Down Expand Up @@ -102,8 +103,14 @@ func UserLogin(c *gin.Context) {
}

// Attach token to browser
c.SetSameSite(http.SameSiteNoneMode)
c.SetCookie("Authorization", tokenString, 3600*24*30, "/", auth.GetFrontendURL(), os.Getenv("APP_ENV") != "development", true)
c.SetSameSite(http.SameSiteLaxMode)

// Trim the protocol and port from the frontend URL
url := strings.TrimPrefix(auth.GetFrontendURL(), "https://")
url = strings.TrimPrefix(url, "http://")
url = strings.Split(url, ":")[0]

c.SetCookie("Authorization", tokenString, 3600*24*30, "/", url, os.Getenv("APP_ENV") != "development", true)
// c.JSON(http.StatusOK, api.UserLoginResp{})
c.JSON(http.StatusOK, gin.H{"token": tokenString}) // TODO: Fix issue where cookie is not being set
}
Expand Down Expand Up @@ -141,7 +148,13 @@ func UserLogout(c *gin.Context) {
}

// Delete token from browser
c.SetCookie("Authorization", "", -1, "/", auth.GetDomain(), os.Getenv("APP_ENV") != "development", true)

// Trim the protocol and port from the frontend URL
url := strings.TrimPrefix(auth.GetFrontendURL(), "https://")
url = strings.TrimPrefix(url, "http://")
url = strings.Split(url, ":")[0]

c.SetCookie("Authorization", "", -1, "/", url, os.Getenv("APP_ENV") != "development", true)

fmt.Printf("user-logout: %d\n", userID)
c.JSON(http.StatusOK, api.UserLogoutResp{})
Expand Down
24 changes: 12 additions & 12 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,26 @@ func init() {

// Start application
func main() {
gin := gin.Default()
r := gin.Default()

// Use CORS middleware
config := cors.DefaultConfig()
config.AllowOrigins = []string{auth.GetFrontendURL()}
config.AllowOrigins = []string{auth.GetFrontendURL(), auth.GetDomain()}
config.AllowCredentials = true
config.AllowHeaders = append(config.AllowHeaders, "Authorization")
gin.Use(cors.New(config))
r.Use(cors.New(config))

gin.POST("/user-login", controllers.UserLogin)
gin.POST("/user-logout", controllers.UserLogout)
gin.GET("/user-get", controllers.UserGet)
r.POST("/user-login", controllers.UserLogin)
r.POST("/user-logout", controllers.UserLogout)
r.GET("/user-get", controllers.UserGet)

gin.POST("/page-create", controllers.PageCreate)
gin.POST("/page-update", controllers.PageUpdate)
gin.GET("/page-get/:page_uuid", controllers.PageGet)
gin.GET("/page-list", controllers.PageList)
gin.POST("/page-delete", controllers.PageDelete)
r.POST("/page-create", controllers.PageCreate)
r.POST("/page-update", controllers.PageUpdate)
r.GET("/page-get/:page_uuid", controllers.PageGet)
r.GET("/page-list", controllers.PageList)
r.POST("/page-delete", controllers.PageDelete)

if err := gin.Run(); err != nil {
if err := r.Run(); err != nil {
panic("Router failed to start Gin: " + err.Error())
}

Expand Down
2 changes: 1 addition & 1 deletion models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,5 @@ type User struct {
Name string `gorm:"not null"`
Picture string `gorm:"not null"`
Credentials []byte `gorm:"type:jsonb;default: '{}'"`
Status string `gorm:"not null;default:'freemium';check:Status IN ('freemium', 'premium', 'enterprise')" json:"status"`
Status string `gorm:"not null;default:'premium';check:Status IN ('freemium', 'premium', 'enterprise')" json:"status"`
}

0 comments on commit d94fc6a

Please sign in to comment.