-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt-server.go
More file actions
62 lines (55 loc) · 1.92 KB
/
jwt-server.go
File metadata and controls
62 lines (55 loc) · 1.92 KB
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
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
"workplace/internal/config"
httpJwt "workplace/internal/http/jwt"
httpMiddleware "workplace/internal/http/middleware"
httpResponse "workplace/internal/http/response"
"workplace/internal/injector"
)
func main() {
var cfg *config.Configuration
var jwtLocal *httpJwt.Jwt
_ = injector.GetContainer().Invoke(func(config *config.Configuration, j *httpJwt.Jwt) {
cfg = config
jwtLocal = j
})
router := gin.Default()
v1 := router.Group("/v1")
{
v1.GET("/login", func(context *gin.Context) {
login := context.Query("login")
password := context.Query("password")
if login == "admin" && password == "test" {
tokenString, err := jwtLocal.CreateTokenByUser(login)
if err != nil {
context.JSON(http.StatusBadRequest, httpResponse.Error(err.Error()))
return
}
context.JSON(http.StatusOK, httpResponse.Success(tokenString))
return
}
context.JSON(http.StatusBadRequest, httpResponse.Error("User not found"))
})
auth := v1.Group("/auth", httpMiddleware.JWTTokenRequiredMiddleware())
{
auth.GET("/hello", func(context *gin.Context) {
claims, err := jwtLocal.GetClaimsByContext(context)
if err != nil {
context.JSON(http.StatusBadRequest, httpResponse.Error("Invalid token"))
return
}
message := fmt.Sprintf("Hello, %s!", claims["user"])
context.JSON(http.StatusOK, httpResponse.Success(message))
return
})
}
}
err := router.Run(cfg.HttpHost + ":" + cfg.HttpPort)
if err != nil {
log.Fatal("Unable to start server:", err)
}
}