changes for the system version 2.0
parent
81314f1aeb
commit
4cbca250f6
12
config.json
12
config.json
|
|
@ -8,23 +8,23 @@
|
|||
"API_PORT": 8111,
|
||||
"DB_HOST": "177.153.50.98",
|
||||
"DB_DRIVER": "postgres",
|
||||
"DB_USER": "pcast",
|
||||
"DB_USER": "postgres",
|
||||
"DB_PASSWORD": "@407Smc837",
|
||||
"DB_NAME": "pcast",
|
||||
"DB_PORT": 5432
|
||||
}
|
||||
},
|
||||
{
|
||||
"releasetype": "homolog",
|
||||
"releasetype": "dev",
|
||||
"data": {
|
||||
"API_PORT": 8112,
|
||||
"DB_HOST": "177.153.50.98",
|
||||
"DB_HOST": "localhost",
|
||||
"DB_DRIVER": "postgres",
|
||||
"DB_USER": "pcasth",
|
||||
"DB_USER": "postgres",
|
||||
"DB_PASSWORD": "@407Smc837",
|
||||
"DB_NAME": "pcasth",
|
||||
"DB_NAME": "pcast",
|
||||
"DB_PORT": 5432
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -1,268 +0,0 @@
|
|||
package controllers
|
||||
|
||||
import (
|
||||
"api/config"
|
||||
"api/database"
|
||||
"api/models"
|
||||
"api/utils"
|
||||
"log"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// MARK: Login
|
||||
func Login(c *fiber.Ctx) error {
|
||||
|
||||
var data map[string]string
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
log.Printf("Bad Request on parse: %v\n", err)
|
||||
return fiber.ErrBadRequest
|
||||
}
|
||||
|
||||
var user models.User
|
||||
|
||||
database.DB.Where("email = ?", data["email"]).First(&user)
|
||||
|
||||
if user.ID == 0 {
|
||||
return c.JSON(fiber.Map{
|
||||
"message": "Usuário não encontrado",
|
||||
"token": ""})
|
||||
}
|
||||
|
||||
if user.Password == nil {
|
||||
return c.JSON(fiber.Map{
|
||||
"message": "Usuário com cadastro imcompleto",
|
||||
"token": ""})
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword(user.Password, []byte(data["password"])); err != nil {
|
||||
return c.JSON(fiber.Map{
|
||||
"message": "Senha inválida",
|
||||
"token": ""})
|
||||
}
|
||||
|
||||
if user.Blocked == "S" {
|
||||
return c.JSON(fiber.Map{
|
||||
"message": "Usuário bloqueado",
|
||||
"token": ""})
|
||||
}
|
||||
|
||||
claims := &jwt.RegisteredClaims{
|
||||
ExpiresAt: &jwt.NumericDate{Time: time.Now().Add(12 * time.Hour)}, // Token expiration time
|
||||
Issuer: strconv.Itoa(int(user.ID)), // User that creates the token
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
|
||||
tk, err := token.SignedString([]byte(config.Conf.ApiSecret))
|
||||
|
||||
if err != nil {
|
||||
return fiber.ErrInternalServerError
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"message": "",
|
||||
"uid": user.ID,
|
||||
"token": tk})
|
||||
}
|
||||
|
||||
// MARK: AddUser
|
||||
func AddUser(c *fiber.Ctx) error {
|
||||
|
||||
var data map[string]string
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
return c.JSON(fiber.Map{
|
||||
"message": "Dados inválidos"})
|
||||
|
||||
}
|
||||
|
||||
if data["name"] == "" || data["email"] == "" || data["url"] == "" || data["cpfcnpj"] == "" || data["password"] == "" || data["channel"] == "" || data["usertype"] == "" || data["companyname"] == "" {
|
||||
return c.JSON(fiber.Map{
|
||||
"message": "Dados inválidos"})
|
||||
}
|
||||
|
||||
passwd, _ := utils.HashPassword(data["password"])
|
||||
|
||||
var user models.User
|
||||
|
||||
database.DB.Where("email = ?", data["email"]).First(&user)
|
||||
|
||||
if user.ID != 0 {
|
||||
return c.JSON(fiber.Map{
|
||||
"message": "Usuário já cadastrado"})
|
||||
}
|
||||
|
||||
database.DB.Where("channel = ?", strings.ToLower(data["channel"])).First(&user)
|
||||
|
||||
if user.ID != 0 {
|
||||
return c.JSON(fiber.Map{
|
||||
"message": "Canal já em uso"})
|
||||
}
|
||||
|
||||
user = models.User{
|
||||
Name: data["name"],
|
||||
Email: data["email"],
|
||||
CompanyName: data["companyname"],
|
||||
Url: data["url"],
|
||||
Password: passwd,
|
||||
Channel: strings.ToLower(data["channel"]),
|
||||
CpfCnpj: data["cpfcnpj"],
|
||||
UserType: data["usertype"],
|
||||
Blocked: "N",
|
||||
Cancelled: "N",
|
||||
}
|
||||
|
||||
database.DB.Create(&user)
|
||||
|
||||
if user.ID == 0 {
|
||||
return c.JSON(fiber.Map{
|
||||
"message": "Erro ao criar usuário"})
|
||||
}
|
||||
|
||||
return c.JSON(user)
|
||||
}
|
||||
|
||||
// MARK: GetOwnUser
|
||||
func GetOwnUser(c *fiber.Ctx) error {
|
||||
|
||||
user, ok := c.Locals("user").(models.User)
|
||||
|
||||
if !ok {
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: User is not admin")
|
||||
}
|
||||
|
||||
return c.JSON(user)
|
||||
}
|
||||
|
||||
// MARK: GetAllUsers
|
||||
func GetAllUsers(c *fiber.Ctx) error {
|
||||
|
||||
var users []models.User
|
||||
|
||||
user := c.Locals("user").(models.User)
|
||||
|
||||
if user.UserType != "A" {
|
||||
return fiber.ErrUnauthorized
|
||||
}
|
||||
|
||||
database.DB.Find(&users)
|
||||
|
||||
// if len(users) == 0 {
|
||||
// return fiber.ErrNotFound
|
||||
// }
|
||||
|
||||
return c.JSON(users)
|
||||
}
|
||||
|
||||
// MARK: GetUserByEmail
|
||||
func GetUserByEmail(c *fiber.Ctx) error {
|
||||
|
||||
user := c.Locals("user").(models.User)
|
||||
|
||||
if user.UserType != "A" {
|
||||
return fiber.ErrUnauthorized
|
||||
}
|
||||
|
||||
email := c.Params("email")
|
||||
|
||||
database.DB.Where("email = ?", email).First(&user)
|
||||
|
||||
// if user.ID == 0 {
|
||||
// return fiber.ErrNotFound
|
||||
// }
|
||||
|
||||
return c.JSON(user)
|
||||
}
|
||||
|
||||
func CreateUser(c *fiber.Ctx) error {
|
||||
|
||||
type CreateUser struct {
|
||||
Email string `json:"email"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
var u CreateUser
|
||||
|
||||
if err := c.BodyParser(&u); err != nil {
|
||||
return fiber.ErrBadRequest
|
||||
}
|
||||
|
||||
user := models.User{
|
||||
Email: u.Email,
|
||||
UserType: u.Type,
|
||||
}
|
||||
|
||||
database.DB.Create(&user)
|
||||
|
||||
return c.JSON(user)
|
||||
}
|
||||
|
||||
// MARK: Checkuser
|
||||
func Checkuser(c *fiber.Ctx) error {
|
||||
|
||||
type Checkuser struct {
|
||||
Email string `json:"email"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
var user models.User
|
||||
var response Checkuser
|
||||
|
||||
email := c.Params("email")
|
||||
|
||||
response.Email = email
|
||||
|
||||
// Check if user exists
|
||||
database.DB.Where("email = ?", email).First(&user)
|
||||
|
||||
if user.ID == 0 {
|
||||
// The user is not found, so it's an eligible tester; let's signalize this
|
||||
response.Type = "T"
|
||||
} else {
|
||||
// The user is found and it's an admin; let's signalize this
|
||||
if user.UserType == "A" {
|
||||
response.Type = "A"
|
||||
}
|
||||
|
||||
// The user is found and it's a pay user; let's signalize this
|
||||
if user.UserType == "U" {
|
||||
// If the user doesn't have a channel, it's a pay user that needs to complete the registration
|
||||
if len(user.Channel) == 0 {
|
||||
response.Type = "RU"
|
||||
} else {
|
||||
response.Type = "U"
|
||||
}
|
||||
}
|
||||
|
||||
// The user is found and it's a social; let's signalize this
|
||||
if user.UserType == "S" {
|
||||
// If the user doesn't have a channel, it's a social user that needs to complete the registration
|
||||
if len(user.Channel) == 0 {
|
||||
response.Type = "RS"
|
||||
} else {
|
||||
response.Type = "S"
|
||||
}
|
||||
}
|
||||
|
||||
if user.Blocked == "S" {
|
||||
// User is blocked
|
||||
response.Type = "UB"
|
||||
} else {
|
||||
if user.Cancelled == "S" {
|
||||
// User is cancelled
|
||||
response.Type = "UC"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Should we insert the user in the database, if it's a tester?
|
||||
|
||||
return c.JSON(response)
|
||||
}
|
||||
|
|
@ -1,108 +0,0 @@
|
|||
package controllers
|
||||
|
||||
import (
|
||||
"api/database"
|
||||
"api/models"
|
||||
|
||||
"github.com/shirou/gopsutil/v3/cpu"
|
||||
"github.com/shirou/gopsutil/v3/disk"
|
||||
"github.com/shirou/gopsutil/v3/host"
|
||||
"github.com/shirou/gopsutil/v3/mem"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// AddServer - Adds a server to the database
|
||||
func AddServer(c *fiber.Ctx) error {
|
||||
|
||||
var data map[string]string
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
return fiber.ErrBadRequest
|
||||
}
|
||||
|
||||
if data["name"] == "" || data["ip"] == "" {
|
||||
return fiber.ErrBadRequest
|
||||
}
|
||||
|
||||
server := models.Server{
|
||||
Name: data["name"],
|
||||
IP: data["ip"],
|
||||
}
|
||||
|
||||
database.DB.Create(&server)
|
||||
|
||||
if server.ID == 0 {
|
||||
return fiber.ErrNotAcceptable
|
||||
}
|
||||
|
||||
return c.JSON(server)
|
||||
}
|
||||
|
||||
// GetAllServers - Returns all servers
|
||||
func GetAllServers(c *fiber.Ctx) error {
|
||||
|
||||
u := c.Locals("user").(models.User)
|
||||
|
||||
if u.UserType != "A" {
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: User is not admin")
|
||||
}
|
||||
|
||||
var servers []models.Server
|
||||
|
||||
database.DB.Find(&servers)
|
||||
|
||||
if len(servers) == 0 {
|
||||
return fiber.ErrNotFound
|
||||
}
|
||||
|
||||
return c.JSON(servers)
|
||||
}
|
||||
|
||||
func GetServerInfo(c *fiber.Ctx) error {
|
||||
|
||||
var diskPercent float64 = 0.0
|
||||
var memoryPercent float64 = 0.0
|
||||
var cpuPercent float64 = 0.0
|
||||
|
||||
// Get info from the host
|
||||
hostStat, _ := host.Info()
|
||||
|
||||
// Get info from the host disks
|
||||
if hostStat.OS == "windows" {
|
||||
var total, free uint64 = 0.0, 0.0
|
||||
partitions, _ := disk.Partitions(false)
|
||||
for _, partition := range partitions {
|
||||
v3, _ := disk.Usage(partition.Device)
|
||||
total = total + v3.Total
|
||||
free = free + v3.Free
|
||||
}
|
||||
diskPercent = (float64(total-free) / float64(total)) * 100
|
||||
} else {
|
||||
diskstat, _ := disk.Usage("/")
|
||||
diskPercent = diskstat.UsedPercent
|
||||
}
|
||||
|
||||
// Get info from the host memory
|
||||
v, _ := mem.VirtualMemory()
|
||||
memoryPercent = v.UsedPercent
|
||||
|
||||
// Get info from the host CPUs
|
||||
cpus := 0
|
||||
v4, _ := cpu.Percent(0, true)
|
||||
for _, cpu := range v4 {
|
||||
cpus++
|
||||
cpuPercent = cpuPercent + cpu
|
||||
}
|
||||
cpuPercent = cpuPercent / float64(cpus)
|
||||
|
||||
c.Set("Content-Type", "application/json; charset=utf-8")
|
||||
|
||||
type result struct {
|
||||
Memory float64 `json:"memory"`
|
||||
CPU float64 `json:"cpu"`
|
||||
Disk float64 `json:"disk"`
|
||||
}
|
||||
|
||||
return c.JSON(result{Memory: memoryPercent, CPU: cpuPercent, Disk: diskPercent})
|
||||
}
|
||||
|
|
@ -1,101 +0,0 @@
|
|||
package controllers
|
||||
|
||||
import (
|
||||
"api/database"
|
||||
"api/models"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func AddEvent(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
var startdt time.Time
|
||||
var err error
|
||||
|
||||
user := c.Locals("user").(models.User)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
return fiber.ErrBadRequest
|
||||
}
|
||||
|
||||
if data["name"] == "" || data["description"] == "" {
|
||||
return fiber.ErrBadRequest
|
||||
}
|
||||
|
||||
if user.Blocked == "S" || user.Cancelled == "S" {
|
||||
return fiber.ErrForbidden
|
||||
}
|
||||
|
||||
dateformat := "02/01/2006 15:04"
|
||||
if data["startDt"] == "" {
|
||||
return fiber.ErrBadRequest
|
||||
} else {
|
||||
startdt, err = time.Parse(dateformat, data["startDt"])
|
||||
if err != nil {
|
||||
return fiber.ErrBadRequest
|
||||
}
|
||||
}
|
||||
|
||||
event := models.Event{
|
||||
Name: data["name"],
|
||||
Description: data["description"],
|
||||
UserId: user.ID,
|
||||
ExpectedDate: startdt,
|
||||
EventType: data["eventtype"],
|
||||
}
|
||||
|
||||
database.DB.Create(&event)
|
||||
|
||||
if event.ID == 0 {
|
||||
return fiber.ErrNotAcceptable
|
||||
}
|
||||
|
||||
return c.JSON(event)
|
||||
}
|
||||
|
||||
// GetAllEvents - Returns all events
|
||||
func GetAllEvents(c *fiber.Ctx) error {
|
||||
|
||||
var events []models.Event
|
||||
|
||||
user := c.Locals("user").(models.User)
|
||||
|
||||
if user.UserType != "A" {
|
||||
return fiber.ErrUnauthorized
|
||||
}
|
||||
|
||||
database.DB.Find(&events)
|
||||
|
||||
if len(events) == 0 {
|
||||
return fiber.ErrNotFound
|
||||
}
|
||||
|
||||
return c.JSON(events)
|
||||
}
|
||||
|
||||
// GetEventsByUser - Returns all events from a user
|
||||
func GetEventsByUser(c *fiber.Ctx) error {
|
||||
|
||||
var events []models.Event
|
||||
|
||||
user := c.Locals("user").(models.User)
|
||||
|
||||
if user.UserType != "A" {
|
||||
return fiber.ErrUnauthorized
|
||||
}
|
||||
|
||||
database.DB.Where("id = ?", c.Params("id")).First(&user)
|
||||
|
||||
if user.ID == 0 {
|
||||
return fiber.ErrUnauthorized
|
||||
}
|
||||
|
||||
database.DB.Where("user_id = ?", user.ID).Find(&events)
|
||||
|
||||
if len(events) == 0 {
|
||||
return fiber.ErrNotFound
|
||||
}
|
||||
|
||||
return c.JSON(events)
|
||||
}
|
||||
|
|
@ -1,52 +1,58 @@
|
|||
package controllers
|
||||
|
||||
import (
|
||||
"api/database"
|
||||
"api/models"
|
||||
"github.com/shirou/gopsutil/v3/cpu"
|
||||
"github.com/shirou/gopsutil/v3/disk"
|
||||
"github.com/shirou/gopsutil/v3/host"
|
||||
"github.com/shirou/gopsutil/v3/mem"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// AddServer - Adds a server to the database
|
||||
func AddCorporation(c *fiber.Ctx) error {
|
||||
func GetServerInfo(c *fiber.Ctx) error {
|
||||
|
||||
var data map[string]string
|
||||
var diskPercent float64 = 0.0
|
||||
var memoryPercent float64 = 0.0
|
||||
var cpuPercent float64 = 0.0
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
return fiber.ErrBadRequest
|
||||
// Get info from the host
|
||||
hostStat, _ := host.Info()
|
||||
|
||||
// Get info from the host disks
|
||||
if hostStat.OS == "windows" {
|
||||
var total, free uint64 = 0.0, 0.0
|
||||
partitions, _ := disk.Partitions(false)
|
||||
for _, partition := range partitions {
|
||||
v3, _ := disk.Usage(partition.Device)
|
||||
total = total + v3.Total
|
||||
free = free + v3.Free
|
||||
}
|
||||
diskPercent = (float64(total-free) / float64(total)) * 100
|
||||
} else {
|
||||
diskstat, _ := disk.Usage("/")
|
||||
diskPercent = diskstat.UsedPercent
|
||||
}
|
||||
|
||||
if data["name"] == "" || data["description"] == "" || data["id"] == "" {
|
||||
return fiber.ErrBadRequest
|
||||
// Get info from the host memory
|
||||
v, _ := mem.VirtualMemory()
|
||||
memoryPercent = v.UsedPercent
|
||||
|
||||
// Get info from the host CPUs
|
||||
cpus := 0
|
||||
v4, _ := cpu.Percent(0, true)
|
||||
for _, cpu := range v4 {
|
||||
cpus++
|
||||
cpuPercent = cpuPercent + cpu
|
||||
}
|
||||
cpuPercent = cpuPercent / float64(cpus)
|
||||
|
||||
c.Set("Content-Type", "application/json; charset=utf-8")
|
||||
|
||||
type result struct {
|
||||
Memory float64 `json:"memory"`
|
||||
CPU float64 `json:"cpu"`
|
||||
Disk float64 `json:"disk"`
|
||||
}
|
||||
|
||||
corp := models.Corporation{
|
||||
Name: data["name"],
|
||||
Description: data["description"],
|
||||
CorporationId: data["id"],
|
||||
}
|
||||
|
||||
database.DB.Create(&corp)
|
||||
|
||||
if corp.ID == 0 {
|
||||
return fiber.ErrNotAcceptable
|
||||
}
|
||||
|
||||
return c.JSON(corp)
|
||||
}
|
||||
|
||||
// GetAllServers - Returns all servers
|
||||
func GetCorporation(c *fiber.Ctx) error {
|
||||
|
||||
u := c.Locals("user").(models.User)
|
||||
|
||||
if u.UserType != "A" {
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: User is not admin")
|
||||
}
|
||||
|
||||
var corps []models.Corporation
|
||||
|
||||
database.DB.Find(&corps)
|
||||
|
||||
return c.JSON(corps)
|
||||
return c.JSON(result{Memory: memoryPercent, CPU: cpuPercent, Disk: diskPercent})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
package controllers
|
||||
|
||||
import (
|
||||
"api/database"
|
||||
"api/models"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func GetUsers(c *fiber.Ctx) error {
|
||||
var users []models.SystemUser
|
||||
|
||||
database.DB.Find(&users)
|
||||
|
||||
return c.JSON(users)
|
||||
}
|
||||
|
||||
func GetGroups(c *fiber.Ctx) error {
|
||||
var groups []models.SystemGroup
|
||||
|
||||
database.DB.Find(&groups)
|
||||
|
||||
return c.JSON(groups)
|
||||
}
|
||||
|
|
@ -70,7 +70,7 @@ func OnUpdate(c *fiber.Ctx) error {
|
|||
|
||||
if len(p.Groups) > 0 {
|
||||
for _, g := range p.Groups {
|
||||
log.Printf("Update %s %s [(%dx%d) %d]\n", g.Channel, g.UpdPub.StartTime, g.VideoWidth, g.VideoHeight, g.UpdPub.ReadBytesSum)
|
||||
log.Printf("======================== Update %s %s [(%dx%d) %d]\n", g.Channel, g.UpdPub.StartTime, g.VideoWidth, g.VideoHeight, g.UpdPub.ReadBytesSum)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -105,7 +105,7 @@ func OnPubStart(c *fiber.Ctx) error {
|
|||
return err
|
||||
}
|
||||
|
||||
log.Printf("Start StreamName %s, UrlParam %s, SessionId %s\n", p.StreamName, p.UrlParam, p.SessionId)
|
||||
log.Printf("======================== Start StreamName %s, UrlParam %s, SessionId %s\n", p.StreamName, p.UrlParam, p.SessionId)
|
||||
|
||||
// TODO: Verify if the key is correct. If not, Kick the Session.
|
||||
// KickSession(p.StreamName, p.SessionId)
|
||||
|
|
@ -122,7 +122,7 @@ func OnPubStop(c *fiber.Ctx) error {
|
|||
if err := c.BodyParser(p); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("Stop Channel %s\n", p.StreamName)
|
||||
log.Printf("======================== Stop Channel %s\n", p.StreamName)
|
||||
return c.SendString("On_Pub_Stop: " + string(c.Body()))
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,8 +2,6 @@ package database
|
|||
|
||||
import (
|
||||
"api/config"
|
||||
"api/models"
|
||||
"api/utils"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
|
|
@ -42,68 +40,6 @@ func ConnectDB() error {
|
|||
return err
|
||||
}
|
||||
|
||||
log.Println("Migrating database tables")
|
||||
|
||||
if result := db.AutoMigrate(&models.User{}); result != nil {
|
||||
return result
|
||||
}
|
||||
|
||||
if result := db.AutoMigrate(&models.Event{}); result != nil {
|
||||
return result
|
||||
}
|
||||
|
||||
if result := db.AutoMigrate(&models.Server{}); result != nil {
|
||||
return result
|
||||
}
|
||||
|
||||
if result := db.AutoMigrate(&models.Transaction{}); result != nil {
|
||||
return result
|
||||
}
|
||||
|
||||
if result := db.AutoMigrate(&models.Corporation{}); result != nil {
|
||||
return result
|
||||
}
|
||||
|
||||
// Count how many servers we have on the database. If none, creates our initial server.
|
||||
var servers []models.Server
|
||||
|
||||
db.Find(&servers)
|
||||
|
||||
if len(servers) == 0 {
|
||||
server := models.Server{
|
||||
Name: "Pcast Main Server",
|
||||
Subdomain: "s1",
|
||||
IP: "177.153.50.98",
|
||||
}
|
||||
|
||||
db.Create(&server)
|
||||
}
|
||||
|
||||
// Count how many users we have on the database. If none, creates our initial admin user.
|
||||
var users []models.User
|
||||
|
||||
db.Find(&users)
|
||||
|
||||
if len(users) == 0 {
|
||||
passwd, _ := utils.HashPassword("123456")
|
||||
|
||||
user := models.User{
|
||||
Name: "Pcast Admin",
|
||||
Email: "pcastlive@pcastlive.com",
|
||||
CompanyName: "PCast",
|
||||
Password: passwd,
|
||||
Url: "https://pcastlive.com",
|
||||
CpfCnpj: "49.083.957/0001-38",
|
||||
Channel: "pcastlive",
|
||||
UserType: "A",
|
||||
Blocked: "N",
|
||||
Cancelled: "N",
|
||||
ServerId: 1,
|
||||
}
|
||||
|
||||
db.Create(&user)
|
||||
}
|
||||
|
||||
DB = db
|
||||
|
||||
return nil
|
||||
|
|
|
|||
1
go.mod
1
go.mod
|
|
@ -4,7 +4,6 @@ go 1.22
|
|||
|
||||
require (
|
||||
github.com/gofiber/fiber/v2 v2.50.0
|
||||
github.com/golang-jwt/jwt/v5 v5.1.0
|
||||
github.com/shirou/gopsutil/v3 v3.23.10
|
||||
github.com/spf13/viper v1.17.0
|
||||
golang.org/x/crypto v0.15.0
|
||||
|
|
|
|||
2
go.sum
2
go.sum
|
|
@ -70,8 +70,6 @@ github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
|||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/gofiber/fiber/v2 v2.50.0 h1:ia0JaB+uw3GpNSCR5nvC5dsaxXjRU5OEu36aytx+zGw=
|
||||
github.com/gofiber/fiber/v2 v2.50.0/go.mod h1:21eytvay9Is7S6z+OgPi7c7n4++tnClWmhpimVHMimw=
|
||||
github.com/golang-jwt/jwt/v5 v5.1.0 h1:UGKbA/IPjtS6zLcdB7i5TyACMgSbOTiR8qzXgw8HWQU=
|
||||
github.com/golang-jwt/jwt/v5 v5.1.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
|
|
|
|||
16
main.go
16
main.go
|
|
@ -2,6 +2,7 @@ package main
|
|||
|
||||
import (
|
||||
"api/config"
|
||||
"api/database"
|
||||
"api/globals"
|
||||
"api/routes"
|
||||
"io"
|
||||
|
|
@ -36,13 +37,16 @@ func main() {
|
|||
// Get release type from command line
|
||||
args := os.Args[1:]
|
||||
|
||||
var releaseType string
|
||||
|
||||
if len(args) == 0 {
|
||||
log.Println("Missing release type")
|
||||
return
|
||||
releaseType = "dev"
|
||||
} else {
|
||||
releaseType = args[0]
|
||||
}
|
||||
|
||||
// Load configurations for the release type
|
||||
if !config.LoadConfigurations(args[0]) {
|
||||
if !config.LoadConfigurations(releaseType) {
|
||||
log.Printf("Invalid release type: %s\n", args[0])
|
||||
return
|
||||
}
|
||||
|
|
@ -75,9 +79,9 @@ func main() {
|
|||
}))
|
||||
|
||||
// Connects to database
|
||||
// if err := database.ConnectDB(); err != nil {
|
||||
// panic("Could not connect to database")
|
||||
// }
|
||||
if err := database.ConnectDB(); err != nil {
|
||||
panic("Could not connect to database")
|
||||
}
|
||||
|
||||
// Setup routes
|
||||
routes.Setup(app)
|
||||
|
|
|
|||
|
|
@ -1,66 +0,0 @@
|
|||
package middlewares
|
||||
|
||||
import (
|
||||
"api/config"
|
||||
"api/models"
|
||||
"api/services"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
var usr models.User
|
||||
|
||||
func Authenticate(c *fiber.Ctx) error {
|
||||
|
||||
apik, _ := base64.StdEncoding.DecodeString(c.Get("X-API-KEY"))
|
||||
|
||||
apikdata := strings.Split(string(apik), ":")
|
||||
|
||||
if len(apikdata) == 2 {
|
||||
usr = services.GetUser(apikdata[0])
|
||||
if usr.ID == 0 {
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: Inexistent user")
|
||||
}
|
||||
c.Locals("user", usr)
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
tk := c.Get("Authorization")
|
||||
|
||||
if tk == "" {
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: No token provided")
|
||||
}
|
||||
|
||||
tokenstr := strings.Split(tk, " ")[1]
|
||||
|
||||
token, err := jwt.Parse(tokenstr, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(config.Conf.ApiSecret), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: "+strings.Replace(err.Error(), "token has invalid claims: ", "", -1))
|
||||
}
|
||||
|
||||
if token.Valid {
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
usr = services.GetUser(claims["iss"].(string))
|
||||
|
||||
if usr.Blocked == "S" {
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: User blocked")
|
||||
}
|
||||
|
||||
if usr.Cancelled == "S" {
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: User cancelled")
|
||||
}
|
||||
|
||||
c.Locals("user", usr)
|
||||
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: Invalid token")
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Channel struct {
|
||||
gorm.Model
|
||||
Name string `gorm:"size:40;not null" json:"name"`
|
||||
Description string `gorm:"not null" json:"description"`
|
||||
CorporationId string
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Corporation struct {
|
||||
gorm.Model
|
||||
CorporationId string
|
||||
Name string `gorm:"size:40;not null" json:"name"`
|
||||
Description string `gorm:"not null" json:"description"`
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Event struct {
|
||||
gorm.Model
|
||||
Name string `gorm:"size:40;not null" json:"name"`
|
||||
Description string `gorm:"not null" json:"description"`
|
||||
ExpectedDate time.Time `gorm:"not null" json:"startDt"`
|
||||
UserId uint `gorm:"size:40;not null" json:"user"`
|
||||
EventType string `gorm:"size:1;not null;default:O" json:"eventtype"` // T = Test, N = Normal
|
||||
Transmitted string `gorm:"size:1;not null;default:N" json:"transmitted"` // Y = Already transmitted, N = Not transmitted yet
|
||||
}
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
package models
|
||||
|
||||
type SystemGroup struct {
|
||||
ID int `gorm:"primaryKey"`
|
||||
Name string `gorm:"size:256"`
|
||||
}
|
||||
|
||||
func (SystemGroup) TableName() string {
|
||||
return "system_group"
|
||||
}
|
||||
|
||||
type SystemProgram struct {
|
||||
ID int `gorm:"primaryKey"`
|
||||
Name string `gorm:"size:256"`
|
||||
Controller string `gorm:"size:256"`
|
||||
}
|
||||
|
||||
type SystemUnit struct {
|
||||
ID int `gorm:"primaryKey"`
|
||||
Name string `gorm:"size:256"`
|
||||
ConnectionName string `gorm:"size:256"`
|
||||
CustomCode string `gorm:"size:256"`
|
||||
}
|
||||
|
||||
type SystemRole struct {
|
||||
ID int `gorm:"primaryKey"`
|
||||
Name string `gorm:"size:256"`
|
||||
CustomCode string `gorm:"size:256"`
|
||||
}
|
||||
|
||||
type SystemPreference struct {
|
||||
ID string `gorm:"primaryKey;size:256"`
|
||||
Value string `gorm:"type:citext"`
|
||||
}
|
||||
|
||||
type SystemUser struct {
|
||||
ID int `gorm:"primaryKey"`
|
||||
Name string `gorm:"size:256"`
|
||||
Login string `gorm:"size:256"`
|
||||
Password string `gorm:"size:256"`
|
||||
Email string `gorm:"size:256"`
|
||||
AcceptedTermPolicy string `gorm:"size:1"`
|
||||
Phone string `gorm:"size:256"`
|
||||
Address string `gorm:"size:256"`
|
||||
FunctionName string `gorm:"size:256"`
|
||||
About string `gorm:"type:citext"`
|
||||
AcceptedTermPolicyAt string `gorm:"size:20"`
|
||||
AcceptedTermPolicyData string `gorm:"type:citext"`
|
||||
FrontpageID int `gorm:"index"`
|
||||
SystemUnitID int `gorm:"index"`
|
||||
Active string `gorm:"size:1"`
|
||||
CustomCode string `gorm:"size:256"`
|
||||
OTPSecret string `gorm:"size:256"`
|
||||
SystemUnit SystemUnit `gorm:"foreignKey:SystemUnitID"`
|
||||
Frontpage SystemProgram `gorm:"foreignKey:FrontpageID"`
|
||||
}
|
||||
|
||||
type SystemUserUnit struct {
|
||||
ID int `gorm:"primaryKey"`
|
||||
SystemUserID int
|
||||
SystemUnitID int
|
||||
SystemUser SystemUser `gorm:"foreignKey:SystemUserID"`
|
||||
SystemUnit SystemUnit `gorm:"foreignKey:SystemUnitID"`
|
||||
}
|
||||
|
||||
type SystemUserGroup struct {
|
||||
ID int `gorm:"primaryKey"`
|
||||
SystemUserID int
|
||||
SystemGroupID int
|
||||
SystemUser SystemUser `gorm:"foreignKey:SystemUserID"`
|
||||
SystemGroup SystemGroup `gorm:"foreignKey:SystemGroupID"`
|
||||
}
|
||||
|
||||
type SystemUserRole struct {
|
||||
ID int `gorm:"primaryKey"`
|
||||
SystemUserID int
|
||||
SystemRoleID int
|
||||
SystemUser SystemUser `gorm:"foreignKey:SystemUserID"`
|
||||
SystemRole SystemRole `gorm:"foreignKey:SystemRoleID"`
|
||||
}
|
||||
|
||||
type SystemGroupProgram struct {
|
||||
ID int `gorm:"primaryKey"`
|
||||
SystemGroupID int
|
||||
SystemProgramID int
|
||||
SystemGroup SystemGroup `gorm:"foreignKey:SystemGroupID"`
|
||||
SystemProgram SystemProgram `gorm:"foreignKey:SystemProgramID"`
|
||||
}
|
||||
|
||||
type SystemUserProgram struct {
|
||||
ID int `gorm:"primaryKey"`
|
||||
SystemUserID int
|
||||
SystemProgramID int
|
||||
SystemUser SystemUser `gorm:"foreignKey:SystemUserID"`
|
||||
SystemProgram SystemProgram `gorm:"foreignKey:SystemProgramID"`
|
||||
}
|
||||
|
||||
type SystemUserOldPassword struct {
|
||||
ID int `gorm:"primaryKey"`
|
||||
SystemUserID int
|
||||
Password string `gorm:"size:256"`
|
||||
CreatedAt string `gorm:"size:20"`
|
||||
SystemUser SystemUser `gorm:"foreignKey:SystemUserID"`
|
||||
}
|
||||
|
||||
type SystemProgramMethodRole struct {
|
||||
ID int `gorm:"primaryKey"`
|
||||
SystemProgramID int
|
||||
SystemRoleID int
|
||||
MethodName string `gorm:"size:256"`
|
||||
SystemProgram SystemProgram `gorm:"foreignKey:SystemProgramID"`
|
||||
SystemRole SystemRole `gorm:"foreignKey:SystemRoleID"`
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
gorm.Model
|
||||
Name string `gorm:"size:40;not null" json:"name"`
|
||||
Subdomain string `gorm:"size:40;not null" json:"subdomain"`
|
||||
IP string `gorm:"size:40;not null" json:"ip"`
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Transaction struct {
|
||||
gorm.Model
|
||||
Email string `gorm:"size:40" json:"email"`
|
||||
PlanOrderID string `gorm:"size:40" json:"planorderid"`
|
||||
Value float64 `gorm:"size:10" json:"value"`
|
||||
PlanStartDate string `gorm:"size:10" json:"planstartdate"`
|
||||
PlanValidUntil string `gorm:"size:10" json:"planvaliduntil"`
|
||||
PlanTitle string `gorm:"size:40" json:"plantitle"`
|
||||
Operation string `gorm:"size:40" json:"operation"`
|
||||
Obs string `gorm:"size:40" json:"obs"`
|
||||
}
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
gorm.Model
|
||||
Name string `gorm:"size:40" json:"name"`
|
||||
CompanyName string `gorm:"size:40" json:"companyname"`
|
||||
Email string `gorm:"size:40;unique" json:"email"`
|
||||
Phone string `gorm:"size:20" json:"phone"`
|
||||
Password []byte `gorm:"size:100;" json:"-"`
|
||||
Channel string `gorm:"size:40" json:"channel"`
|
||||
Url string `gorm:"size:40" json:"url"`
|
||||
CpfCnpj string `gorm:"size:20" json:"cpfcnpj"`
|
||||
UserType string `gorm:"size:2;default:T" json:"usertype"` // A - Admin, U - User, S - Social, T - Test
|
||||
Blocked string `gorm:"size:1;default:N" json:"blocked"`
|
||||
Cancelled string `gorm:"size:1;default:N" json:"cancelled"`
|
||||
ServerId uint `gorm:"not null;default:1" json:"serverid"`
|
||||
TestStatus string `gorm:"size:2" json:"status"` // TR - Teste Realizado, TS - Aguardando
|
||||
}
|
||||
|
|
@ -2,7 +2,6 @@ package routes
|
|||
|
||||
import (
|
||||
"api/controllers"
|
||||
"api/middlewares"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
|
@ -16,11 +15,8 @@ func Setup(app *fiber.App) {
|
|||
|
||||
app.Get("/health", controllers.GetServerInfo)
|
||||
|
||||
app.Post("/login", controllers.Login)
|
||||
app.Post("/register", controllers.AddUser)
|
||||
app.Post("/create", controllers.CreateUser)
|
||||
|
||||
app.Get("/checkuser/:email", controllers.Checkuser)
|
||||
app.Get("/users", controllers.GetUsers)
|
||||
app.Get("/groups", controllers.GetGroups)
|
||||
|
||||
// Webhooks
|
||||
app.Post("/on_server_start", controllers.ServerStart)
|
||||
|
|
@ -29,23 +25,4 @@ func Setup(app *fiber.App) {
|
|||
app.Post("/on_pub_start", controllers.OnPubStart)
|
||||
app.Post("/on_pub_stop", controllers.OnPubStop)
|
||||
app.Post("/on_sub_start", controllers.OnSubStart)
|
||||
|
||||
app.Get("/corporations", controllers.GetCorporation)
|
||||
app.Get("/user", controllers.GetOwnUser)
|
||||
|
||||
// Protected routes. Needs login before.
|
||||
protected := app.Group("/")
|
||||
|
||||
protected.Use(middlewares.Authenticate)
|
||||
|
||||
protected.Get("servers", controllers.GetAllServers)
|
||||
protected.Post("server", controllers.AddServer)
|
||||
|
||||
protected.Get("users", controllers.GetAllUsers)
|
||||
protected.Get("users/:email", controllers.GetUserByEmail)
|
||||
protected.Post("user", controllers.AddUser)
|
||||
|
||||
protected.Post("event", controllers.AddEvent)
|
||||
protected.Get("events", controllers.GetAllEvents)
|
||||
protected.Get("events/:id", controllers.GetEventsByUser)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +0,0 @@
|
|||
package services
|
||||
|
||||
import (
|
||||
"api/database"
|
||||
"api/models"
|
||||
)
|
||||
|
||||
func GetUser(id string) models.User {
|
||||
var user models.User
|
||||
|
||||
database.DB.Where("id = ?", id).First(&user)
|
||||
|
||||
return user
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
package services
|
||||
|
||||
import (
|
||||
"api/database"
|
||||
"api/models"
|
||||
)
|
||||
|
||||
func GetUserByEmail(email string) models.SystemUser {
|
||||
var user models.SystemUser
|
||||
|
||||
database.DB.Where("email = ?", email).Find(&user)
|
||||
|
||||
return user
|
||||
}
|
||||
Loading…
Reference in New Issue