-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathback.go
214 lines (170 loc) · 6.24 KB
/
back.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package main
import (
"context"
"database/sql"
"fmt"
"net/http"
"sync"
"github.com/fvbock/endless"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore"
"github.com/gin-gonic/gin"
"github.com/logto-io/go/client"
"github.com/jackc/pgx/v5/pgconn"
_ "github.com/jackc/pgx/v5/stdlib"
)
const ErrPostgerDuplicateKeyValueCode = "23505"
type Server struct {
DB *sql.DB
LogtoConfig *client.LogtoConfig
}
type BackendResponse struct {
Data interface{} `json:"data"`
Error string `json:"error"`
}
func (b *Server) GetEntries(ctx *gin.Context) {
entries := map[string]string{}
var tempName string
var tempUrl string
result, err := b.DB.QueryContext(ctx, "SELECT internal_name, remote_url FROM links")
if err != nil {
ctx.Error(fmt.Errorf("result: %v, error: %w", result, err))
ctx.AbortWithStatusJSON(http.StatusInternalServerError, BackendResponse{Error: "cannot get entries from db", Data: map[string]string{}})
return
}
for result.Next() {
err = result.Scan(&tempName, &tempUrl)
if err != nil {
ctx.Error(fmt.Errorf("db scan error: %w", err))
ctx.AbortWithStatusJSON(http.StatusInternalServerError, BackendResponse{Error: "cannot parse entries from db", Data: map[string]string{}})
return
}
entries[tempName] = tempUrl
}
ctx.JSON(http.StatusOK, BackendResponse{Error: "", Data: entries})
}
func (b *Server) AddEntry(ctx *gin.Context) {
var newEntry map[string]string
if err := ctx.BindJSON(&newEntry); err != nil {
ctx.Error(err)
ctx.AbortWithStatusJSON(http.StatusBadRequest, BackendResponse{Data: nil, Error: "parsing request data failed"})
return
}
if len(newEntry) != 1 {
ctx.Error(fmt.Errorf("payload length is not 1"))
ctx.AbortWithStatusJSON(http.StatusBadRequest, BackendResponse{Data: nil, Error: "json must contain one element"})
return
}
for key, value := range newEntry {
result, err := b.DB.ExecContext(ctx, "INSERT INTO links (internal_name, remote_url) VALUES ($1, $2)", key, value)
if err != nil {
switch err := err.(type) {
case *pgconn.PgError:
if err.Code == ErrPostgerDuplicateKeyValueCode {
ctx.Error(fmt.Errorf("entry with for request '%v' already exist", newEntry))
ctx.AbortWithStatusJSON(http.StatusBadRequest, BackendResponse{Data: nil, Error: "entry with name already exist"})
return
}
}
ctx.Error(fmt.Errorf("result: %v, error: %w", result, err))
ctx.AbortWithStatusJSON(http.StatusInternalServerError, BackendResponse{Error: "cannot push entry to db", Data: nil})
return
}
}
ctx.JSON(http.StatusCreated, BackendResponse{Error: "", Data: newEntry})
}
func (b *Server) GetEntry(ctx *gin.Context) {
name := ctx.Param("name")
row := b.DB.QueryRowContext(ctx, "SELECT remote_url FROM links WHERE internal_name = $1", name)
if row.Err() != nil {
ctx.Error(fmt.Errorf("failed quering db: %w", row.Err()))
ctx.AbortWithStatusJSON(http.StatusInternalServerError, BackendResponse{Data: nil, Error: "cannot get entry from db"})
return
}
var remoteUrl string
row.Scan(&remoteUrl)
if remoteUrl == "" {
ctx.Error(fmt.Errorf("requested id is not found in db"))
ctx.AbortWithStatusJSON(http.StatusNotFound, BackendResponse{Data: nil, Error: "entry not found"})
return
}
ctx.Redirect(http.StatusMovedPermanently, remoteUrl)
}
func (b *Server) DeleteEntry(ctx *gin.Context) {
var entryToDelete string
if err := ctx.BindJSON(&entryToDelete); err != nil {
ctx.Error(err)
ctx.AbortWithStatusJSON(http.StatusBadRequest, BackendResponse{Data: nil, Error: "parsing request data failed"})
return
}
result, err := b.DB.ExecContext(ctx, "DELETE from links WHERE internal_name = $1", entryToDelete)
if err != nil {
ctx.Error(fmt.Errorf("result: %v, error: %w", result, err))
ctx.AbortWithStatusJSON(http.StatusInternalServerError, BackendResponse{Error: "cannot push entry to db", Data: nil})
return
}
fmt.Println(result)
rowsAffected, err := result.RowsAffected()
if err != nil {
ctx.Error(fmt.Errorf("rows_affected: %v, error: %w", rowsAffected, err))
ctx.AbortWithStatusJSON(http.StatusInternalServerError, BackendResponse{Error: "cannot get info from db", Data: nil})
return
}
if rowsAffected == 0 {
ctx.Error(fmt.Errorf("%v not removed from db (looks like it didnt exist)", rowsAffected))
ctx.AbortWithStatusJSON(http.StatusNotFound, BackendResponse{Data: nil, Error: "entry didn't exist in db"})
}
ctx.JSON(http.StatusOK, BackendResponse{Error: "", Data: entryToDelete})
}
func newInstance(ctx context.Context, postgresPath string, logtoEndpoint string, logtoAppId string, logtoAppSecret string) (*Server, error) {
db, err := sql.Open("pgx", postgresPath)
if err != nil {
return nil, fmt.Errorf("cannot open connect to db: %w", err)
}
err = db.PingContext(ctx)
if err != nil {
return nil, fmt.Errorf("cannot ping db: %w", err)
}
logtoConfig := &client.LogtoConfig{
Endpoint: logtoEndpoint,
AppId: logtoAppId,
AppSecret: logtoAppSecret,
}
return &Server{
DB: db,
LogtoConfig: logtoConfig,
}, nil
}
func (b *Server) ValidateLogtoAuth(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(
b.LogtoConfig,
&SessionStorage{session: session},
)
if !logtoClient.IsAuthenticated() {
ctx.Error(fmt.Errorf("client is not authenticated via logto"))
ctx.AbortWithStatusJSON(http.StatusForbidden, BackendResponse{Data: nil, Error: "client is not authenticated via logto"})
return
}
ctx.Next()
}
func (s *Server) StartServer(wg *sync.WaitGroup) {
defer wg.Done()
router := gin.Default()
router.GET("/api/v1/:name/", s.GetEntry)
// idk what session secret is :^(
store := memstore.NewStore([]byte("your session secret"))
router.Use(sessions.Sessions("logto-session", store))
router.Static("/assets", "static/dist/assets/")
router.StaticFile("/oneko.gif", "static/assets/oneko.gif")
router.StaticFile("/", "static/dist/index.html")
router.StaticFile("/admin", "static/dist/index.html")
router.GET("/sign-in", s.SignIn)
router.GET("auth-callback", s.AuthCallback)
requiesAuthGroup := router.Group("/")
requiesAuthGroup.Use(s.ValidateLogtoAuth)
requiesAuthGroup.POST("/api/v1/entries", s.AddEntry)
requiesAuthGroup.GET("/api/v1/entries", s.GetEntries)
router.DELETE("/api/v1/entries", s.DeleteEntry)
endless.ListenAndServe("localhost:8080", router)
}