/
main.go
281 lines (221 loc) · 6.87 KB
/
main.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package main
import (
"encoding/json"
"fmt"
"html/template"
"net/http"
"os"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
gba "github.com/revzim/azgba/core/gba"
)
var (
// kTokenExpTime time.Duration
kJWTSecret []byte
kGBACtx gba.GBAContext
kAcceptedClientIDs []string
)
func init() {
// kTokenExpTime = 3
kJWTSecret = []byte("SECRETKEY1")
kGBACtx = gba.MainContext
kAcceptedClientIDs = []string{
"jon",
"dz1",
"mz1",
"az1",
"cz1",
"rz1",
}
}
func jwtTokenParseClaims(tokenString string) (*jwt.Token, error) {
claims := jwt.MapClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return kJWTSecret, nil
})
// handle err
if err != nil {
fmt.Println("\nToken parsewithclaims failed", token, err)
return nil, err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
fmt.Println("\nID FROM PARSED CLAIMS: ", claims["id"])
} else {
fmt.Println("\nError in token: ", claims, token.Valid)
return nil, fmt.Errorf("error: %+v: %b", claims, token.Valid)
}
return token, nil
}
func signin(c echo.Context) error {
m := make(map[string]interface{})
m["Form"] = map[string]interface{}{
"HashBlock": "TESTHASH",
"LoginVals": []string{"email", "password"},
"BtnSubmitString": "SUBMIT",
}
// m["TokenExpTime"] = fmt.Sprintf("%d", kTokenExpTime)
formatScriptJS := func(base string, fName string) string {
return fmt.Sprintf(`<script src="/%s/%s"></script>`, base, fName)
}
gbaMap := make(map[string]interface{})
files := formatScriptJS("GBA/IodineGBA/includes", "TypedArrayShim.js")
for _, fileName := range kGBACtx.CoreFileNames {
files += formatScriptJS(kGBACtx.Core, fileName)
// filesArr = append(filesArr, fmt.Sprintf("/%s/%s", core, fileName))
}
for _, fileName := range kGBACtx.FrontEndFileNames {
files += formatScriptJS(kGBACtx.PreFrontEndFiles, fileName)
}
gbaMap["FileNames"] = files
gbaMap["SelectedGameText"] = "Select a game!"
gbaMap["BIOSURL"] = "/auth/files/bios/gba_bios.bin"
m["GBA"] = gbaMap
fms := template.FuncMap{
"html": func(value interface{}) template.HTML {
return template.HTML(fmt.Sprint(value))
},
"html2": func(value interface{}, str string) template.HTML {
return template.HTML(fmt.Sprintf("%s/%s", str, value))
},
}
template, err := template.New(fmt.Sprintf("%s.html", "login")).Funcs(fms).ParseFiles("public/templates/login.html")
if err != nil {
fmt.Println("ERROR=>", err)
}
return template.Execute(c.Response().Writer, m)
}
func login(c echo.Context) error {
// username := c.FormValue("username")
// Throws unauthorized error
// isAccepted := false
// for _, id := range kAcceptedClientIDs {
// if id == username {
// isAccepted = true
// break
// }
// }
// if !isAccepted {
// return echo.ErrUnauthorized
// }
// Set custom claims
// claims := &gba.JWTCustomClaims{
// username,
// true,
// "",
// jwt.StandardClaims{
// ExpiresAt: time.Now().Add(time.Second * kTokenExpTime).Unix(),
// },
// }
// // Create token with claims
// token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// // Generate encoded token and send it as response.
// t, err := token.SignedString(kJWTSecret)
// if err != nil {
// return err
// }
// c.Response().Header().Set("Authorization", "Bearer "+t)
// c.Set("token", t)
// return c.HTML(http.StatusOK, "<p class='text-dark'>"+t+"</p>")
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(*gba.JWTCustomClaims)
id := claims.ID
exp := claims.Exp
gamesListMap := make(map[string]string)
gamesListRaw := json.RawMessage(kGBACtx.GamesListStr)
gamesListBytes, err := gamesListRaw.MarshalJSON()
if err != nil {
fmt.Println("Err", err)
}
err = json.Unmarshal(gamesListBytes, &gamesListMap)
c.Response().Header().Set("Authorization", "Bearer "+user.Raw)
return c.JSON(http.StatusOK, echo.Map{
// "token": t,
"games": gamesListMap,
"id": id,
"exp": exp,
})
}
func handleRestricted(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
_, err := jwtTokenParseClaims(user.Raw)
if err != nil {
return echo.ErrUnauthorized
}
claims := user.Claims.(*gba.JWTCustomClaims) //(jwt.MapClaims)
id := claims.ID //["name"]
fmt.Println("handleRestriced: name | token | qparams ==>", id)
c.Response().Header().Set("Authorization", "Bearer "+user.Raw)
return handleGBA(c)
}
func handleGBA(c echo.Context) error {
game := c.Param("name")
m := make(map[string]interface{})
m["OK"] = true
m["JSList"] = ``
m["GameName"] = game
m["Game"] = kGBACtx.GameTemplateStr
template := template.New("gba.html").Funcs(kGBACtx.FuncMap)
_, err := template.ParseFiles("public/templates/gba.html")
if err != nil {
fmt.Println("ERROR=>", err)
}
return template.Execute(c.Response().Writer, m)
}
func handleFiles(c echo.Context) error {
// token := c.Get("user")
user := c.Get("user").(*jwt.Token)
_, err := jwtTokenParseClaims(user.Raw)
if err != nil {
return echo.ErrUnauthorized
}
claims := user.Claims.(*gba.JWTCustomClaims) //(jwt.MapClaims)
id := claims.ID //["name"]
fmt.Println("handleFiles: name ==>", id)
path := c.Param("id")
fileName := c.Param("name")
filePath := fmt.Sprintf("private/%s/%s", path, fileName)
// fmt.Println("DOWNLOAD FILE LINK:", filePath)
return c.File(filePath)
}
func main() {
e := echo.New()
// Static js/css/fonts/etc files
e.Static("/", "public/vendor")
// Logger Middleware
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: "method=${method}, uri=${uri}, status=${status}\n",
}))
// Recover Middleware
e.Use(middleware.Recover())
// Unauthenticated route
e.GET("/", signin)
// Restricted group
r := e.Group("/auth")
// Configure middleware with the custom claims type
config := middleware.JWTConfig{
Claims: &gba.JWTCustomClaims{},
SigningKey: kJWTSecret,
Skipper: func(c echo.Context) bool {
// fmt.Printf("jwtconfig path: %+v", c.Path())
// parent := c.Param("next")
// if c.Path() == "/auth/login" {
// return true
// }
fmt.Println(c.Request().Header.Get("Authorization"))
// path := c.Param("id")
// game := c.Param("name")
// fmt.Println("jwtconfig: path | game ==>", path, " | ", game)
// if c.Path() == "/auth" || c.Path() == "/auth/:next/:id/:name" || c.Path() == "/auth/files/:id/:name" {
// return true
// }
return false
},
}
r.Use(middleware.JWTWithConfig(config))
// Login route
r.POST("/login", login)
r.GET("", handleRestricted)
r.GET("/files/:id/:name", handleFiles)
e.Logger.Fatal(e.Start(os.Args[1]))
}