-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
260 lines (240 loc) · 7.38 KB
/
api.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
package api
import (
"bytes"
"crypto/rand"
"encoding/base32"
"flag"
"net/http"
jwt "github.com/dgrijalva/jwt-go"
"github.com/jinzhu/gorm"
"github.com/pressly/chi"
"github.com/pressly/chi/middleware"
chiRender "github.com/pressly/chi/render"
"github.com/titouanfreville/popcubeapi/configs"
"github.com/titouanfreville/popcubeapi/datastores"
"github.com/titouanfreville/popcubeapi/models"
"github.com/titouanfreville/popcubeapi/utils"
renderPackage "github.com/unrolled/render"
)
type saveDb struct {
db *gorm.DB
}
// Key type to be sure the context key is the one we want.
type key string
// Token A JWT Token. Different fields will be used depending on whether you're
// creating or parsing/verifying a token.
// type Token struct {
// Raw string // The raw token. Populated when you Parse a token
// Method SigningMethod // The signing method used or to be used
// Header map[string]interface{} // The first segment of the token
// Claims Claims // The second segment of the token
// Signature string // The third segment of the token. Populated when you Parse a token
// Valid bool // Is the token valid? Populated when you Parse/Verify a token
// }
var (
hmacSampleSecret []byte
tokenAuth *JwtAuth
userToken *jwt.Token
encoding = base32.NewEncoding("ybndrfg8ejkmcpqxot1uwisza345h769")
render = renderPackage.New()
routes = flag.Bool("routes", false, "Generate router documentation")
dbStore = saveDb{}
error401 = utils.NewAPIError(401, "unauthorized", "You did not login into the app. Please login to access those resources")
error422 = utils.NewAPIError(422, "parse.request.body", "Request json object not correct.")
error503 = utils.NewAPIError(503, "database.maintenance", "Database is currently in maintenance state. We are doing our best to get it back online ASAP.")
)
func newRandomString(length int) string {
var b bytes.Buffer
str := make([]byte, length+8)
rand.Read(str)
encoder := base32.NewEncoder(encoding, &b)
encoder.Write(str)
encoder.Close()
b.Truncate(length)
return b.String()
}
func initAuth() {
secret := newRandomString(100)
hmacSampleSecret = []byte(secret)
tokenAuth = New("HS256", hmacSampleSecret, hmacSampleSecret)
}
// createToken create JWT auth token for current login user
func createToken(user models.User) (string, error) {
claims := jwt.MapClaims{
"name": user.Username,
"email": user.Email,
"role": user.IDRole,
}
unsignedToken := *jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := unsignedToken.SignedString(hmacSampleSecret)
if err != nil {
return "", err
}
return tokenString, nil
}
// newRouter initialise api serveur.
func newRouter() *chi.Mux {
return chi.NewRouter()
}
// initMiddleware initialise middlewares for router
func initMiddleware(router *chi.Mux) {
router.Use(middleware.RequestID)
router.Use(middleware.RealIP)
router.Use(middleware.Logger)
router.Use(middleware.Recoverer)
router.Use(middleware.StripSlashes)
router.Use(middleware.Timeout(5 * 1000))
router.Use(middleware.Heartbeat("/heartbeat"))
router.Use(middleware.CloseNotify)
}
// basicRoutes set basic routes for the API
func basicRoutes(router *chi.Mux) {
// swagger:route GET / Test hello
//
// Hello World
//
// Responses:
// 200: generalOk
// default: genericError
router.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Welcome to PopCube api. Let's chat all together :O"))
})
// swagger:route GET /ping Test ping
//
// Pong
//
// Test api ping
//
// Responses:
// 200: generalOk
// default: genericError
router.Get("/ping", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("pong"))
})
router.Get("/heartbeat", func(w http.ResponseWriter, r *http.Request) {})
// swagger:route GET /panic Test panic
//
// Should result in 500
//
// Test panic cautching
//
// Responses:
// 500: genericError
// default: genericError
router.Get("/panic", func(w http.ResponseWriter, r *http.Request) {
panic("C'est la panique, panique, panique. Sur le périphérique")
})
// swagger:route POST /login Login login
//
// Try to log user in
//
// Login user with provided USERNAME && Password
//
// Responses:
// 200: loginOk
// 404: incorrectIds
// 422: wrongEntity
// 503: databaseError
router.Post("/login", loginMiddleware)
// swagger:route POST /user Users newPublicUser
//
// New user
//
// This will create an user for organisation if organisation is Public OR Email match parametetered emails
//
// Responses:
// 201: userObjectSuccess
// 422: wrongEntity
// 503: databaseError
// default: genericError
router.Post("/publicuser", newPublicUser)
}
// loginMiddleware login funcion providing user && jwt auth token
func loginMiddleware(w http.ResponseWriter, r *http.Request) {
var data struct {
Login string `json:"login"`
Password string `json:"password"`
OmitID interface{} `json:"id,omitempty"`
}
store := datastores.Store()
response := loginOk{}
db := dbStore.db
request := r.Body
err := chiRender.Bind(request, &data)
if err != nil {
render.JSON(w, error422.StatusCode, error422)
return
}
if err := db.DB().Ping(); err == nil {
user, err := store.User().Login(data.Login, data.Password, db)
if err == nil {
var terr error
response.User = user
response.Token, terr = createToken(user)
if terr == nil {
render.JSON(w, 200, response)
return
}
render.JSON(w, err.StatusCode, err)
return
}
}
render.JSON(w, error503.StatusCode, error503)
}
func newPublicUser(w http.ResponseWriter, r *http.Request) {
var data struct {
User *models.User
OmitID interface{} `json:"id,omitempty"`
}
store := datastores.Store()
db := dbStore.db
request := r.Body
err := chiRender.Bind(request, &data)
if err != nil || data.User == nil {
render.JSON(w, error422.StatusCode, error422)
} else {
if err := db.DB().Ping(); err == nil {
err := store.User().Save(data.User, db)
if err == nil {
render.JSON(w, 201, data.User)
} else {
render.JSON(w, err.StatusCode, err)
}
} else {
render.JSON(w, error503.StatusCode, error503)
}
}
}
// StartAPI initialise the api with provided host and port.
func StartAPI(hostname string, port string, DbConnectionInfo *configs.DbConnection) {
router := newRouter()
// Init DB connection
user := DbConnectionInfo.User
db := DbConnectionInfo.Database
pass := DbConnectionInfo.Password
host := DbConnectionInfo.Host
dbport := DbConnectionInfo.Port
dbStore.db = datastores.Store().InitConnection(user, db, pass, host, dbport)
initAuth()
initMiddleware(router)
basicRoutes(router)
initAvatarRoute(router)
initChannelRoute(router)
initEmojiRoute(router)
initFolderRoute(router)
initMessageRoute(router)
initOrganisationRoute(router)
initParameterRoute(router)
initRoleRoute(router)
initUserRoute(router)
// Passing -routes to the program will generate docs for the above
// router definition. See the `routes.json` file in this folder for
// the output.
// log.Println(docgen.JSONRoutesDoc(router))
// log.Println(docgen.BuildDoc(router))
// log.Println(docgen.MarkdownRoutesDoc(router, docgen.MarkdownOpts{
// ProjectPath: "github.com/titouanfreville/popcubeapi",
// Intro: "Welcomme to popcube user api.",
// }))
http.ListenAndServe(hostname+":"+port, router)
}