This commit is contained in:
ngn
2023-11-12 17:43:23 +03:00
parent 8c1552d639
commit 498a54cd20
68 changed files with 1983 additions and 301 deletions

141
api/routes/admin.go Normal file
View File

@ -0,0 +1,141 @@
package routes
import (
"log"
"net/http"
"os"
"strings"
"time"
"github.com/gofiber/fiber/v2"
"github.com/mattn/go-sqlite3"
"github.com/ngn13/website/api/util"
)
var Token string = util.CreateToken()
func AuthMiddleware(c *fiber.Ctx) error {
if c.Path() == "/admin/login" {
return c.Next()
}
if c.Get("Authorization") != Token {
return util.ErrAuth(c)
}
return c.Next()
}
func Login(c *fiber.Ctx) error{
if c.Query("pass") != os.Getenv("PASSWORD") {
return c.Status(http.StatusUnauthorized).JSON(fiber.Map{
"error": "Authentication failed",
})
}
return c.Status(http.StatusOK).JSON(fiber.Map{
"error": "",
"token": Token,
})
}
func Logout(c *fiber.Ctx) error{
Token = util.CreateToken()
return c.Status(http.StatusOK).JSON(fiber.Map{
"error": "",
})
}
func RemoveService(c *fiber.Ctx) error {
name := c.Query("name")
if name == "" {
util.ErrBadData(c)
}
_, err := DB.Exec("DELETE FROM services WHERE name = ?", name)
if util.ErrorCheck(err, c){
return util.ErrServer(c)
}
return util.NoError(c)
}
func AddService(c *fiber.Ctx) error {
var service Service
if c.BodyParser(&service) != nil {
return util.ErrBadJSON(c)
}
if service.Name == "" || service.Desc == "" || service.Url == "" {
return util.ErrBadData(c)
}
rows, err := DB.Query("SELECT * FROM services WHERE name = ?", service.Name)
if util.ErrorCheck(err, c){
return util.ErrServer(c)
}
if rows.Next() {
rows.Close()
return util.ErrExists(c)
}
rows.Close()
_, err = DB.Exec(
"INSERT INTO services(name, desc, url) values(?, ?, ?)",
service.Name, service.Desc, service.Url,
)
if util.ErrorCheck(err, c){
return util.ErrServer(c)
}
return util.NoError(c)
}
func RemovePost(c *fiber.Ctx) error{
var id = c.Query("id")
if id == "" {
return util.ErrBadData(c)
}
_, err := DB.Exec("DELETE FROM posts WHERE id = ?", id)
if util.ErrorCheck(err, c){
return util.ErrServer(c)
}
return util.NoError(c)
}
func AddPost(c *fiber.Ctx) error{
var post Post
post.Public = 1
if c.BodyParser(&post) != nil {
return util.ErrBadJSON(c)
}
if post.Title == "" || post.Author == "" || post.Content == "" {
return util.ErrBadData(c)
}
post.Date = time.Now().Format("02/01/06")
log.Println(post.Date)
post.ID = TitleToID(post.Title)
_, err := DB.Exec(
"INSERT INTO posts(id, title, author, date, content, public, vote) values(?, ?, ?, ?, ?, ?, ?)",
post.ID, post.Title, post.Author, post.Date, post.Content, post.Public, post.Vote,
)
if err != nil && strings.Contains(err.Error(), sqlite3.ErrConstraintUnique.Error()) {
return util.ErrExists(c)
}
if util.ErrorCheck(err, c){
return util.ErrExists(c)
}
return util.NoError(c)
}

162
api/routes/blog.go Normal file
View File

@ -0,0 +1,162 @@
package routes
import (
"database/sql"
"log"
"net/http"
"github.com/gofiber/fiber/v2"
"github.com/ngn13/website/api/util"
)
func BlogDb(db *sql.DB) {
_, err := db.Exec(`
CREATE TABLE IF NOT EXISTS posts(
id TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
author TEXT NOT NULL,
date TEXT NOT NULL,
content TEXT NOT NULL,
public INTEGER NOT NULL,
vote INTEGER NOT NULL
);
`)
DB = db
if err != nil {
log.Fatal("Error creating table: "+err.Error())
}
}
func GetIP(c *fiber.Ctx) string {
if c.Get("X-Real-IP") != "" {
return c.Get("X-Real-IP")
}
return c.IP()
}
func VoteStat(c *fiber.Ctx) error{
var id = c.Query("id")
if id == "" {
return util.ErrBadData(c)
}
for i := 0; i < len(votelist); i++ {
if votelist[i].Client == GetIP(c) && votelist[i].Post == id {
return c.JSON(fiber.Map {
"error": "",
"result": votelist[i].Status,
})
}
}
return c.Status(http.StatusNotFound).JSON(util.ErrorJSON("Client never voted"))
}
func VoteSet(c *fiber.Ctx) error{
var id = c.Query("id")
var to = c.Query("to")
voted := false
if id == "" || (to != "upvote" && to != "downvote") {
return util.ErrBadData(c)
}
for i := 0; i < len(votelist); i++ {
if votelist[i].Client == GetIP(c) && votelist[i].Post == id && votelist[i].Status == to {
return c.Status(http.StatusForbidden).JSON(util.ErrorJSON("Client already voted"))
}
if votelist[i].Client == GetIP(c) && votelist[i].Post == id && votelist[i].Status != to {
voted = true
}
}
post, msg := GetPostByID(id)
if msg != ""{
return c.Status(http.StatusNotFound).JSON(util.ErrorJSON(msg))
}
vote := post.Vote+1
if to == "downvote" {
vote = post.Vote-1
}
if to == "downvote" && voted {
vote = vote-1
}
if to == "upvote" && voted {
vote = vote+1
}
_, err := DB.Exec("UPDATE posts SET vote = ? WHERE title = ?", vote, post.Title)
if util.ErrorCheck(err, c){
return util.ErrServer(c)
}
for i := 0; i < len(votelist); i++ {
if votelist[i].Client == GetIP(c) && votelist[i].Post == id && votelist[i].Status != to {
votelist[i].Status = to
return util.NoError(c)
}
}
var entry = Vote{}
entry.Client = GetIP(c)
entry.Status = to
entry.Post = id
votelist = append(votelist, entry)
return util.NoError(c)
}
func GetPost(c *fiber.Ctx) error{
var id = c.Query("id")
if id == "" {
return util.ErrBadData(c)
}
post, msg := GetPostByID(id)
if msg != ""{
return c.Status(http.StatusNotFound).JSON(util.ErrorJSON(msg))
}
return c.JSON(fiber.Map {
"error": "",
"result": post,
})
}
func SumPost(c *fiber.Ctx) error{
var posts []Post = []Post{}
rows, err := DB.Query("SELECT * FROM posts")
if util.ErrorCheck(err, c) {
return util.ErrServer(c)
}
for rows.Next() {
var post Post
err := PostFromRow(&post, rows)
if util.ErrorCheck(err, c) {
return util.ErrServer(c)
}
if post.Public == 0 {
continue
}
if len(post.Content) > 255{
post.Content = post.Content[0:250]
}
posts = append(posts, post)
}
rows.Close()
return c.JSON(fiber.Map {
"error": "",
"result": posts,
})
}

74
api/routes/global.go Normal file
View File

@ -0,0 +1,74 @@
package routes
import (
"database/sql"
"strings"
)
// ############### BLOG ###############
type Post struct {
ID string `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
Date string `json:"date"`
Content string `json:"content"`
Public int `json:"public"`
Vote int `json:"vote"`
}
var votelist = []Vote{}
type Vote struct {
Post string
Client string
Status string
}
func PostFromRow(post *Post, rows *sql.Rows) error{
err := rows.Scan(&post.ID, &post.Title, &post.Author, &post.Date, &post.Content, &post.Public, &post.Vote)
if err != nil {
return err
}
return nil
}
func GetPostByID(id string) (Post, string) {
var post Post = Post{}
post.Title = "NONE"
rows, err := DB.Query("SELECT * FROM posts WHERE id = ?", id)
if err != nil{
return post, "Server error"
}
success := rows.Next()
if !success {
rows.Close()
return post, "Post not found"
}
err = PostFromRow(&post, rows)
if err != nil {
rows.Close()
return post, "Server error"
}
rows.Close()
if post.Title == "NONE" {
return post, "Post not found"
}
return post, ""
}
func TitleToID(name string) string{
return strings.ToLower(strings.ReplaceAll(name, " ", ""))
}
// ############### SERVICES ###############
type Service struct {
Name string `json:"name"`
Desc string `json:"desc"`
Url string `json:"url"`
}

45
api/routes/routes.go Normal file
View File

@ -0,0 +1,45 @@
package routes
import (
"database/sql"
"net/http"
"github.com/gofiber/fiber/v2"
)
var DB *sql.DB
func Setup(app *fiber.App, db *sql.DB){
// database init
DB = db
// index route
app.Get("/", func(c *fiber.Ctx) error {
return c.Send([]byte("o/"))
})
// blog routes
app.Get("/blog/sum", SumPost)
app.Get("/blog/get", GetPost)
app.Get("/blog/vote/set", VoteSet)
app.Get("/blog/vote/status", VoteStat)
// service routes
app.Get("/services/all", GetServices)
// admin routes
app.Use("/admin*", AuthMiddleware)
app.Get("/admin/login", Login)
app.Get("/admin/logout", Logout)
app.Put("/admin/service/add", AddService)
app.Delete("/admin/service/remove", RemoveService)
app.Put("/admin/blog/add", AddPost)
app.Delete("/admin/blog/remove", RemovePost)
// 404 page
app.All("*", func(c *fiber.Ctx) error {
return c.Status(http.StatusNotFound).JSON(fiber.Map {
"error": "Requested endpoint not found",
})
})
}

48
api/routes/services.go Normal file
View File

@ -0,0 +1,48 @@
package routes
import (
"database/sql"
"log"
"github.com/gofiber/fiber/v2"
"github.com/ngn13/website/api/util"
)
func ServicesDb(db *sql.DB) {
_, err := db.Exec(`
CREATE TABLE IF NOT EXISTS services(
name TEXT NOT NULL UNIQUE,
desc TEXT NOT NULL,
url TEXT NOT NULL
);
`)
if err != nil {
log.Fatal("Error creating table: "+err.Error())
}
}
func GetServices(c *fiber.Ctx) error {
var services []Service = []Service{}
rows, err := DB.Query("SELECT * FROM services")
if util.ErrorCheck(err, c) {
return util.ErrServer(c)
}
for rows.Next() {
var service Service
err := rows.Scan(&service.Name, &service.Desc, &service.Url)
if err != nil {
log.Println("Error scaning services row: "+err.Error())
continue
}
services = append(services, service)
}
rows.Close()
return c.JSON(fiber.Map {
"error": "",
"result": services,
})
}