update auth.go, database.go, docs.go, forum.go, go.mod, go.sum, main.go, post_schema.go, role.go, server.go, service.go, swagger.json, swagger.yaml, thread_schema.go

This commit is contained in:
redtea committed 2024-10-21 12:00:00 +03:00
1 parent 42c7f5795d
commit 43505548f7
14 files changed
+855

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
package repository
import (
"esforum"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type Config struct {
Host string
Port string
Username string
Password string
DBName string
}
func NewDB(cfg Config) (*gorm.DB, error) {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
cfg.Username,
cfg.Password,
cfg.Host,
cfg.Port,
cfg.DBName)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
return nil, err
}
err = db.Set("gorm:table_options", "CHARSET=utf8mb4").AutoMigrate(&esforum.Post{})
if err != nil {
return nil, err
}
err = db.Set("gorm:table_options", "CHARSET=utf8mb4").AutoMigrate(&esforum.Thread{})
if err != nil {
return nil, err
}
return db, nil
}
+71
View File
@@ -0,0 +1,71 @@
package repository
import (
"esforum"
"fmt"
"gorm.io/gorm"
)
type PostSchema struct {
db *gorm.DB
}
func NewPostSchema(db *gorm.DB) *PostSchema {
return &PostSchema{db: db}
}
func (r PostSchema) CreatePost(title string, content string, thread int64) (*esforum.Post, error) {
post := &esforum.Post{
Title: title,
Content: content,
Thread: thread,
}
err := r.db.Create(post).Error
return post, err
}
func (r PostSchema) GetPost(id int64) (*esforum.Post, error) {
post := esforum.Post{}
err := r.db.Find(&post, "id = ?", id).Error
if post.Id == -1 {
err = fmt.Errorf("unknown thread %d", id)
}
return &post, err
}
func (r PostSchema) DeletePost(id int64) error {
post := esforum.Post{}
err := r.db.Find(&post, "id = ?", id).Error
if post.Id == -1 {
err = fmt.Errorf("unknown thread %d", id)
}
r.db.Delete(post)
return err
}
func (r PostSchema) FindPostsByThread(thread int64, start, limit int) []int64 {
var result []esforum.Post
r.db.Find(&result, "thread = ?", thread).Limit(limit).Offset(start).Find(&result)
var ans = make([]int64, len(result))
for i, res := range result {
ans[i] = res.Id
}
return ans
}
func (r PostSchema) GetPosts(start, limit int) []int64 {
var result []esforum.Post
r.db.Select("id").Limit(limit).Offset(start).Find(&result)
var ans = make([]int64, len(result))
for i, res := range result {
ans[i] = res.Id
}
return ans
}
func (r PostSchema) GetPostsCount() int64 {
var count int64 = 0
r.db.Model(&esforum.Post{}).Count(&count)
return count
}
+68
View File
@@ -0,0 +1,68 @@
package repository
import (
"esforum"
"fmt"
"gorm.io/gorm"
)
type ThreadSchema struct {
db *gorm.DB
}
func NewThreadSchema(db *gorm.DB) *ThreadSchema {
return &ThreadSchema{db: db}
}
func (r ThreadSchema) CreateThread(title string) (*esforum.Thread, error) {
thread := &esforum.Thread{
Title: title,
}
err := r.db.Create(thread).Error
return thread, err
}
func (r ThreadSchema) GetThread(id int64) (*esforum.Thread, error) {
thread := esforum.Thread{}
err := r.db.Find(&thread, "id = ?", id).Error
if thread.Id == -1 {
err = fmt.Errorf("unknown thread %d", id)
}
return &thread, err
}
func (r ThreadSchema) FindThread(title string) (*esforum.Thread, error) {
thread := esforum.Thread{}
err := r.db.Find(&thread, "title = ?", title).Error
if thread.Id == -1 {
err = fmt.Errorf("unknown thread %s", title)
}
return &thread, err
}
func (r ThreadSchema) DeleteThread(id int64) error {
thread := esforum.Thread{}
err := r.db.Find(&thread, "id = ?", id).Error
if thread.Id == -1 {
err = fmt.Errorf("unknown thread %d", id)
}
r.db.Delete(thread)
return err
}
func (r ThreadSchema) GetThreads(start, limit int) []int64 {
var result []esforum.Thread
r.db.Select("id").Limit(limit).Offset(start).Find(&result)
var ans = make([]int64, len(result))
for i, res := range result {
ans[i] = res.Id
}
return ans
}
func (r ThreadSchema) GetThreadsCount() int64 {
var count int64 = 0
r.db.Model(&esforum.Thread{}).Count(&count)
return count
}
+156
View File
@@ -0,0 +1,156 @@
package service
import (
"bytes"
"encoding/json"
"esforum"
"fmt"
"io"
"net/http"
"os"
)
const AUTH_URL = "https://auth.easystartup.su/api"
type AuthService struct {
}
func NewAuthService() *AuthService {
return &AuthService{}
}
func (s *AuthService) Authorize(header string) (*esforum.AuthorizedUser, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", AUTH_URL+"/user/self", nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", header)
req.Header.Add("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(resp.Body)
// Check if the response status is 200 OK
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to authozire: %d %s\nheader: %s", resp.StatusCode, resp.Status, header)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var result esforum.AuthorizedUser
err = json.Unmarshal(body, &result)
if err != nil {
return nil, err
}
return &result, nil
}
func (s *AuthService) AuthorizeById(id int64) (*esforum.AuthorizedUser, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", fmt.Sprintf(AUTH_URL+"/user/%d", id), nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+os.Getenv("ADMIN_TOKEN"))
req.Header.Add("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(resp.Body)
// Check if the response status is 200 OK
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to authozire: %d %s", resp.StatusCode, resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var result esforum.AuthorizedUser
err = json.Unmarshal(body, &result)
if err != nil {
return nil, err
}
return &result, nil
}
func (s *AuthService) AuthorizeAndUpdatePicture(header string, picUrl string) (*esforum.AuthorizedUser, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", AUTH_URL+"/user/self", nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", header)
req.Header.Add("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(resp.Body)
// Check if the response status is 200 OK
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to authozire: %d %s\nheader: %s", resp.StatusCode, resp.Status, header)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var result esforum.AuthorizedUser
err = json.Unmarshal(body, &result)
if err != nil {
return nil, err
}
result.PictureURL = picUrl
requestBody, _ := json.Marshal(result)
req, err = http.NewRequest("POST", AUTH_URL+"/user/self", bytes.NewBuffer(requestBody))
if err != nil {
return nil, err
}
req.Header.Add("Authorization", header)
req.Header.Add("Accept", "application/json")
_, err = client.Do(req)
if err != nil {
return nil, err
}
return &result, nil
}
+21
View File
@@ -0,0 +1,21 @@
package service
import (
"esforum"
)
type Authorization interface {
Authorize(header string) (*esforum.AuthorizedUser, error)
AuthorizeById(id int64) (*esforum.AuthorizedUser, error)
AuthorizeAndUpdatePicture(header string, picUrl string) (*esforum.AuthorizedUser, error)
}
type Service struct {
Authorization
}
func NewService() *Service {
return &Service{
Authorization: NewAuthService(),
}
}
+51
View File
@@ -0,0 +1,51 @@
package util
import (
"encoding/json"
"esforum"
"fmt"
"io"
"net/http"
"github.com/gin-gonic/gin"
)
func MatchRole(c *gin.Context, role string) bool {
client := &http.Client{}
req, err := http.NewRequest("GET", fmt.Sprintf("https://auth.easystartup.su/api/user/self"), nil)
if err != nil {
return false
}
req.Header.Add("Authorization", c.GetHeader("Authorization"))
req.Header.Add("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return false
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(resp.Body)
// Check if the response status is 200 OK
if resp.StatusCode != http.StatusOK {
return false
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return false
}
var result esforum.AuthorizedUser
err = json.Unmarshal(body, &result)
if err != nil {
return false
}
return result.Access == role
}