-
Notifications
You must be signed in to change notification settings - Fork 1
/
segments.go
96 lines (89 loc) · 2.45 KB
/
segments.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"database/sql"
"fmt"
"github.com/securityfirst/umbrella-api/models"
"github.com/securityfirst/umbrella-api/utils"
"strings"
"time"
"github.com/gosexy/to"
"github.com/gin-gonic/gin"
)
func (um *Umbrella) getSegments(c *gin.Context) {
segmentList, err := um.getAllPublishedSegments(c)
utils.CheckErr(err)
um.checkErr(c, err)
um.JSON(c, 200, segmentList)
}
func (um *Umbrella) AddSegment(c *gin.Context) {
var json models.Segment
c.Bind(&json)
fmt.Printf("%+v", json)
if json.Title == "" || json.Category < 1 {
c.JSON(400, gin.H{"error": "One or several fields missing. Please check and try again"})
return
}
user := c.MustGet("user").(models.User)
segment := models.Segment{Title: strings.TrimSpace(json.Title), Body: strings.TrimSpace(json.Body), Category: json.Category, Status: "submitted", CreatedAt: time.Now().Unix(), Author: user.Id}
switch json.DifficultyString {
case "advanced":
segment.Difficulty = 2
case "expert":
segment.Difficulty = 3
default:
segment.Difficulty = 1
}
if user.Role == 1 {
segment.Status = "published"
segment.ApprovedBy = user.Id
segment.ApprovedAt = time.Now().Unix()
}
err := um.Db.Insert(&segment)
um.checkErr(c, err)
c.JSON(200, segment)
}
func (um *Umbrella) EditSegment(c *gin.Context) {
var json models.Segment
c.Bind(&json)
segmentId := to.Int64(c.Params.ByName("id"))
if segmentId != 0 && (json.Title != "" || json.SubTitle != "" || json.Body != "" || json.Category != 0) {
segment, err := um.getSegmentById(c, segmentId)
if err != nil {
if err == sql.ErrNoRows {
c.JSON(404, gin.H{"error": "Not found"})
return
}
um.checkErr(c, err)
}
if json.Title != "" {
segment.Title = strings.TrimSpace(json.Title)
}
if json.Body != "" {
segment.Body = strings.TrimSpace(json.Body)
}
_, err = um.Db.Update(&segment)
um.checkErr(c, err)
c.JSON(200, segment)
return
}
c.JSON(400, gin.H{"error": "One or several fields missing. Please check and try again"})
}
func (um *Umbrella) DeleteSegment(c *gin.Context) {
segmentId := to.Int64(c.Params.ByName("id"))
if segmentId != 0 {
segment, err := um.getSegmentById(c, segmentId)
if err != nil {
if err == sql.ErrNoRows {
c.JSON(404, gin.H{"error": "Not found"})
return
}
um.checkErr(c, err)
}
_, err = um.Db.Delete(&segment)
um.checkErr(c, err)
c.JSON(200, gin.H{"response": "Success"})
return
} else {
c.JSON(404, gin.H{"error": "Requested resource could not be found"})
}
}