-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
103 lines (85 loc) · 2.37 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
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"time"
"github.com/appleboy/gin-jwt"
"github.com/gin-gonic/gin"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/whatdacode/GoREST/config"
"github.com/whatdacode/GoREST/controllers"
"github.com/whatdacode/GoREST/database"
"github.com/whatdacode/GoREST/models"
"golang.org/x/crypto/bcrypt"
)
func main() {
database.Migrations()
router := gin.Default()
router.Use(RequestLogger())
authMiddleware := &jwt.GinJWTMiddleware{
Realm: "OurRealm",
Key: []byte("OurSecretKey"),
Timeout: time.Hour,
MaxRefresh: time.Hour,
Authenticator: func(email string, password string, c *gin.Context) (string, bool) {
var user models.User
db := config.Connect()
db.First(&user, "email = ?", email)
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
return email, false
}
return email, true
},
// Authorizator: func(userId string, c *gin.Context) bool {
// if userId == "admin" {
// return true
// }
// return false
// },
Unauthorized: func(c *gin.Context, code int, message string) {
c.JSON(code, gin.H{
"code": code,
"message": message,
})
},
TokenLookup: "header:Authorization",
TimeFunc: time.Now,
}
api := router.Group("/api/v1/")
{
api.POST("/login", authMiddleware.LoginHandler)
usersWithAuth := api.Group("/users")
usersWithAuth.Use(authMiddleware.MiddlewareFunc())
{
usersWithAuth.GET("/", controllers.GetUsers)
usersWithAuth.GET("/:id", controllers.GetUserDetail)
usersWithAuth.PATCH("/:id", controllers.UpdateUserDetail)
usersWithAuth.DELETE("/:id", controllers.DeleteUser)
}
users := api.Group("/users")
{
users.POST("/", controllers.CreateUser)
}
}
router.Run()
}
// RequestLogger is used for logging each http request in our API.
// thanks to https://stackoverflow.com/users/3011570/emb
func RequestLogger() gin.HandlerFunc {
return func(c *gin.Context) {
buf, _ := ioutil.ReadAll(c.Request.Body)
rdr1 := ioutil.NopCloser(bytes.NewBuffer(buf))
rdr2 := ioutil.NopCloser(bytes.NewBuffer(buf)) //We have to create a new Buffer, because rdr1 will be read.
fmt.Println(readBody(rdr1)) // Print request body
c.Request.Body = rdr2
c.Next()
}
}
func readBody(reader io.Reader) string {
buf := new(bytes.Buffer)
buf.ReadFrom(reader)
s := buf.String()
return s
}