Skip to content

Commit 81c7ccb

Browse files
committed
Separated logic in server.go into other files
1 parent 37cf30c commit 81c7ccb

File tree

5 files changed

+391
-315
lines changed

5 files changed

+391
-315
lines changed

server/category.go

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"log"
6+
"net/http"
7+
"strconv"
8+
9+
"github.com/labstack/echo/v4"
10+
"go.mongodb.org/mongo-driver/bson"
11+
)
12+
13+
func GetCat(c echo.Context) error {
14+
id, _ := strconv.Atoi(c.QueryParam("id"))
15+
var result *Category
16+
filter := bson.D{{"categoryID", id}}
17+
18+
// Find a category
19+
err := collection.FindOne(context.TODO(), filter).Decode(&result)
20+
if err != nil {
21+
log.Fatal(err)
22+
}
23+
24+
return c.JSON(http.StatusOK, H{
25+
"category": result,
26+
})
27+
}
28+
29+
func NewCat(c echo.Context) error {
30+
catID, _ := strconv.Atoi(c.FormValue("id"))
31+
index, _ := strconv.Atoi(c.FormValue("index"))
32+
33+
category := Category{
34+
categoryID: catID,
35+
categoryName: c.FormValue("name"),
36+
index: index,
37+
}
38+
39+
_, err := collection.InsertOne(context.TODO(), category)
40+
if err != nil {
41+
log.Fatal(err)
42+
}
43+
return c.JSON(http.StatusOK, H{})
44+
}
45+
46+
func PatchCat(c echo.Context) error {
47+
categoryID, _ := strconv.Atoi(c.FormValue("id"))
48+
categoryName := c.FormValue("name")
49+
index, _ := strconv.Atoi(c.FormValue("index"))
50+
filter := bson.D{{"categoryID", categoryID}}
51+
update := bson.D{
52+
{"$set", bson.D{
53+
{"categoryName", categoryName},
54+
{"index", index},
55+
}},
56+
}
57+
58+
// Find a category by id and update it
59+
_, err := collection.UpdateOne(context.TODO(), filter, update)
60+
if err != nil {
61+
log.Fatal(err)
62+
}
63+
64+
return c.JSON(http.StatusOK, H{})
65+
}
66+
67+
func DeleteCat(c echo.Context) error {
68+
id, _ := strconv.Atoi(c.FormValue("id"))
69+
filter := bson.D{{"categoryID", id}}
70+
71+
// Find a category by id and delete it
72+
_, err := collection.DeleteOne(context.TODO(), filter)
73+
if err != nil {
74+
log.Fatal(err)
75+
}
76+
77+
return c.JSON(http.StatusOK, H{})
78+
}

server/login.go

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"crypto/sha256"
6+
"log"
7+
"net/http"
8+
"time"
9+
10+
"github.com/dgrijalva/jwt-go"
11+
"github.com/labstack/echo/v4"
12+
"go.mongodb.org/mongo-driver/bson"
13+
"gopkg.in/ldap.v2"
14+
)
15+
16+
func auth(c echo.Context) error {
17+
// Connect to UNSW LDAP server
18+
l, err := ldap.Dial("tcp", "ad.unsw.edu.au")
19+
if err != nil {
20+
log.Fatal(err)
21+
}
22+
23+
// Attempt to sign in using credentials
24+
zid := c.FormValue("zid")
25+
hashedZID := sha256.Sum256([]byte(zid))
26+
stringZID := string(hashedZID[:])
27+
username := zid + "ad.unsw.edu.au"
28+
password := c.FormValue("password")
29+
30+
err = l.Bind(username, password)
31+
if err != nil {
32+
log.Fatal(err)
33+
}
34+
35+
// Retrieve first name from Identity Manager
36+
baseDN := "OU=IDM_People,OU=IDM,DC=ad,DC=unsw,DC=edu,DC=au"
37+
searchScope := ldap.ScopeWholeSubtree
38+
aliases := ldap.NeverDerefAliases
39+
retrieveAttributes := []string{"givenName"}
40+
searchFilter := "cn=" + username //cn = common name
41+
42+
searchRequest := ldap.NewSearchRequest(
43+
baseDN, searchScope, aliases, 0, 0, false,
44+
searchFilter, retrieveAttributes, nil,
45+
)
46+
47+
searchResult, err := l.Search(searchRequest)
48+
if err != nil {
49+
log.Fatal(err)
50+
}
51+
52+
// Encode user details into a JWT and turn it into a string
53+
jwtKey := []byte("secret_text")
54+
userFound := searchResult.Entries[0]
55+
expirationTime := time.Now().Add(time.Hour * 24)
56+
claims := &Claims{
57+
hashedZID: hashedZID,
58+
firstName: userFound.GetAttributeValue("firstName"),
59+
StandardClaims: jwt.StandardClaims{
60+
ExpiresAt: expirationTime.Unix(),
61+
},
62+
}
63+
tokenJWT := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
64+
tokenString, _ := tokenJWT.SignedString(jwtKey)
65+
66+
// Insert a new user into the collection if user has never logged in before
67+
// Or update the existing token if it has expired
68+
user := User{
69+
userID: stringZID,
70+
userToken: tokenString,
71+
role: "user", // Change this???
72+
}
73+
74+
var isValidUser *User
75+
userFilter := bson.D{{"userID", stringZID}}
76+
err = collection.FindOne(context.TODO(), userFilter).Decode(&isValidUser)
77+
78+
if isValidUser == nil { // Never logged in before
79+
_, err = collection.InsertOne(context.TODO(), user)
80+
if err != nil {
81+
log.Fatal(err)
82+
}
83+
} else { // Logged in before - check validity of token
84+
claims = &Claims{}
85+
decodedToken, _ := jwt.ParseWithClaims(isValidUser.userToken, claims, func(token *jwt.Token) (interface{}, error) {
86+
return jwtKey, nil
87+
})
88+
decodedTokenString, _ := decodedToken.SignedString(jwtKey)
89+
90+
if !decodedToken.Valid { // Logged in before but token is invalid - replace with new token
91+
filter := bson.D{{"userID", stringZID}}
92+
update := bson.D{
93+
{"$set", bson.D{
94+
{"userToken", decodedTokenString},
95+
}},
96+
}
97+
_, err = collection.UpdateOne(context.TODO(), filter, update)
98+
if err != nil {
99+
log.Fatal(err)
100+
}
101+
}
102+
}
103+
104+
return c.JSON(http.StatusOK, H{
105+
"token": tokenString,
106+
})
107+
}

server/post.go

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"log"
6+
"net/http"
7+
"strconv"
8+
"time"
9+
10+
"github.com/labstack/echo/v4"
11+
"go.mongodb.org/mongo-driver/bson"
12+
"go.mongodb.org/mongo-driver/mongo"
13+
"go.mongodb.org/mongo-driver/mongo/options"
14+
)
15+
16+
func GetPost(c echo.Context) error {
17+
var result *Post
18+
id, _ := strconv.Atoi(c.QueryParam("id"))
19+
category := c.QueryParam("category")
20+
21+
// Search for post by id and category
22+
filter := bson.D{{"postID", id}, {"category", category}}
23+
err := collection.FindOne(context.TODO(), filter).Decode(&result)
24+
if err != nil {
25+
log.Fatal(err)
26+
}
27+
return c.JSON(http.StatusOK, H{
28+
"post": result,
29+
})
30+
}
31+
32+
func GetAllPosts(c echo.Context) error {
33+
count, _ := strconv.Atoi(c.QueryParam("id"))
34+
cat := c.QueryParam("category")
35+
36+
findOptions := options.Find()
37+
if count != 10 {
38+
findOptions.SetLimit(int64(count))
39+
} else {
40+
findOptions.SetLimit(10)
41+
}
42+
43+
var posts []*Post
44+
var cur *mongo.Cursor
45+
var err error
46+
47+
if cat == "" { // No specified category
48+
cur, err = collection.Find(context.TODO(), bson.D{{}}, findOptions)
49+
} else {
50+
filter := bson.D{{"post_category", cat}}
51+
cur, err = collection.Find(context.TODO(), filter, findOptions)
52+
}
53+
54+
if err != nil {
55+
log.Fatal(err)
56+
}
57+
58+
// Iterate through all results
59+
for cur.Next(context.TODO()) {
60+
var elem Post
61+
err := cur.Decode(&elem)
62+
if err != nil {
63+
log.Fatal(err)
64+
}
65+
66+
posts = append(posts, &elem)
67+
}
68+
69+
return c.JSON(http.StatusOK, H{
70+
"posts": posts,
71+
})
72+
}
73+
74+
func NewPost(c echo.Context) error {
75+
id, _ := strconv.Atoi(c.FormValue("id"))
76+
category, _ := strconv.Atoi(c.FormValue("category"))
77+
showinMenu, _ := strconv.ParseBool(c.FormValue("showInMenu"))
78+
79+
post := Post{
80+
postID: id,
81+
postTitle: c.FormValue("title"),
82+
postSubtitle: c.FormValue("subtitle"),
83+
postType: c.FormValue("type"),
84+
postCategory: category,
85+
createdOn: time.Now(),
86+
lastEditedOn: time.Now(),
87+
postContent: c.FormValue("content"),
88+
postLinkGithub: c.FormValue("linkGithub"),
89+
postLinkFacebook: c.FormValue("linkFacebook"),
90+
showInMenu: showinMenu,
91+
}
92+
93+
_, err := collection.InsertOne(context.TODO(), post)
94+
if err != nil {
95+
log.Fatal(err)
96+
}
97+
98+
return c.JSON(http.StatusOK, H{})
99+
}
100+
101+
func UpdatePost(c echo.Context) error {
102+
postID, _ := strconv.Atoi(c.FormValue("id"))
103+
postTitle := c.FormValue("title")
104+
postSubtitle := c.FormValue("subtitle")
105+
postType := c.FormValue("type")
106+
postCategory := c.FormValue("category")
107+
postContent := c.FormValue("content")
108+
postLinkGithub := c.FormValue("linkGithub")
109+
postLinkFacebook := c.FormValue("linkFacebook")
110+
showinMenu, _ := strconv.ParseBool(c.FormValue("showInMenu"))
111+
112+
filter := bson.D{{"postID", postID}}
113+
update := bson.D{
114+
{"$set", bson.D{
115+
{"postTitle", postTitle},
116+
{"postSubtitle", postSubtitle},
117+
{"postType", postType},
118+
{"postCategory", postCategory},
119+
{"lastEditedOn", time.Now()},
120+
{"postContent", postContent},
121+
{"postLinkGithub", postLinkGithub},
122+
{"postLinkFacebook", postLinkFacebook},
123+
{"showinMenu", showinMenu},
124+
}},
125+
}
126+
127+
// Find a post by id and update it
128+
_, err := collection.UpdateOne(context.TODO(), filter, update)
129+
if err != nil {
130+
log.Fatal(err)
131+
}
132+
133+
return c.JSON(http.StatusOK, H{})
134+
}
135+
136+
func DeletePost(c echo.Context) error {
137+
id, _ := strconv.Atoi(c.FormValue("id"))
138+
filter := bson.D{{"postID", id}}
139+
140+
// Find a post by id and delete it
141+
_, err := collection.DeleteOne(context.TODO(), filter)
142+
if err != nil {
143+
log.Fatal(err)
144+
}
145+
146+
return c.JSON(http.StatusOK, H{})
147+
}

0 commit comments

Comments
 (0)