Commit f84e7607d3c434e8e06cc329600d4a0df6ae7e96

Authored by Marko Tikvić
1 parent 9933169c81
Exists in master and in 1 other branch v2

added dictionary; improved http utility; json_utility now supports oracle and mysql drivers

... ... @@ -15,12 +15,13 @@ import (
15 15 const OneDay = time.Hour * 24
16 16 const OneWeek = OneDay * 7
17 17 const saltSize = 32
18   -const appName = "korisnicki-centar"
19   -const secret = "korisnicki-centar-api"
  18 +
  19 +var appName = "webutility"
  20 +var secret = "webutility"
20 21  
21 22 type Role struct {
22 23 Name string `json:"name"`
23   - ID int `json:"id"`
  24 + ID int32 `json:"id"`
24 25 }
25 26  
26 27 // TokenClaims are JWT token claims.
... ... @@ -29,20 +30,26 @@ type TokenClaims struct {
29 30 TokenType string `json:"token_type"`
30 31 Username string `json:"username"`
31 32 Role string `json:"role"`
32   - RoleID int `json:"role_id"`
  33 + RoleID int32 `json:"role_id"`
33 34 ExpiresIn int64 `json:"expires_in"`
34 35  
35 36 // extending a struct
36 37 jwt.StandardClaims
37 38 }
38 39  
  40 +func InitJWT(appName, secret string) {
  41 + appName = appName
  42 + secret = secret
  43 +}
  44 +
39 45 // ValidateCredentials hashes pass and salt and returns comparison result with resultHash
40   -func ValidateCredentials(pass, salt, resultHash string) bool {
  46 +func ValidateCredentials(pass, salt, resultHash string) (bool, error) {
41 47 hash, _, err := CreateHash(pass, salt)
42 48 if err != nil {
43   - return false
  49 + return false, err
44 50 }
45   - return hash == resultHash
  51 + res := hash == resultHash
  52 + return res, nil
46 53 }
47 54  
48 55 // CreateHash hashes str using SHA256.
... ...
... ... @@ -16,10 +16,7 @@ func NotFoundHandler(w http.ResponseWriter, req *http.Request) {
16 16 if req.Method == "OPTIONS" {
17 17 return
18 18 }
19   - ErrorResponse(w, req, http.StatusNotFound, []HttpErrorDesc{
20   - {"en", "Not found."},
21   - {"rs", "Traženi resurs ne postoji."},
22   - })
  19 + NotFound(w, req, "Not found")
23 20 }
24 21  
25 22 // SetDefaultHeaders set's default headers for an HTTP response.
... ...
... ... @@ -3,6 +3,7 @@ package webutility
3 3 import (
4 4 "database/sql"
5 5 "encoding/json"
  6 + "errors"
6 7 "fmt"
7 8 "io"
8 9 "net/http"
... ... @@ -21,6 +22,7 @@ var (
21 22 activeProject string
22 23  
23 24 inited bool
  25 + driver string
24 26 )
25 27  
26 28 var logger *gologger.Logger
... ... @@ -79,8 +81,12 @@ func DecodeJSON(r io.Reader, v interface{}) error {
79 81 return json.NewDecoder(r).Decode(v)
80 82 }
81 83  
82   -// LoadPayloadsdetaData loads all payloads' information into 'metadata' variable.
83   -func LoadPayloadsMetadata(db *sql.DB, project string) error {
  84 +// InitPayloadsMetadata loads all payloads' information into 'metadata' variable.
  85 +func InitPayloadsMetadata(drv string, db *sql.DB, project string) error {
  86 + if drv != "ora" && drv != "mysql" {
  87 + return errors.New("driver not supported")
  88 + }
  89 + driver = drv
84 90 metadataDB = db
85 91 activeProject = project
86 92  
... ... @@ -138,7 +144,7 @@ func initMetadata(project string) error {
138 144 p := Payload{}
139 145 err := json.Unmarshal([]byte(load), &p)
140 146 if err != nil {
141   - logger.Log("couldn't init: '%s' metadata: %s\n%s\n", name, err.Error(), load)
  147 + logger.Log("webutility: couldn't init: '%s' metadata: %s\n%s\n", name, err.Error(), load)
142 148 } else {
143 149 success++
144 150 metadata[name] = p
... ... @@ -146,7 +152,7 @@ func initMetadata(project string) error {
146 152 count++
147 153 }
148 154 perc := float32(success/count) * 100.0
149   - logger.Log("loaded %d/%d (%.1f%%) entities\n", success, count, perc)
  155 + logger.Log("webutility: loaded %d/%d (%.1f%%) entities\n", success, count, perc)
150 156  
151 157 return nil
152 158 }
... ... @@ -161,7 +167,7 @@ func hotload(n int) {
161 167 entity_type
162 168 from entities where projekat = ` + fmt.Sprintf("'%s'", activeProject))
163 169 if err != nil {
164   - logger.Log("hotload failed: %v\n", err)
  170 + logger.Log("webutility: hotload failed: %v\n", err)
165 171 time.Sleep(time.Duration(n) * time.Second)
166 172 continue
167 173 }
... ... @@ -180,7 +186,7 @@ func hotload(n int) {
180 186 rows.Close()
181 187  
182 188 if rows.Err() != nil {
183   - logger.Log("hotload rset error: %v\n", rows.Err())
  189 + logger.Log("webutility: hotload rset error: %v\n", rows.Err())
184 190 time.Sleep(time.Duration(n) * time.Second)
185 191 continue
186 192 }
... ... @@ -217,7 +223,7 @@ func refreshMetadata(entities []string) {
217 223 p := Payload{}
218 224 err := json.Unmarshal([]byte(load), &p)
219 225 if err != nil {
220   - logger.Log("couldn't refresh: '%s' metadata: %s\n%s\n", e, err.Error(), load)
  226 + logger.Log("webutility: couldn't refresh: '%s' metadata: %s\n%s\n", e, err.Error(), load)
221 227 } else {
222 228 metadata[e] = p
223 229 }
... ... @@ -226,14 +232,13 @@ func refreshMetadata(entities []string) {
226 232 }
227 233 }
228 234  
229   -/*
230 235 func UpdateEntityModels(command string) (total, upd, add int, err error) {
231 236 if command != "force" && command != "missing" {
232   - return total, 0, 0, errors.New("uknown command: " + command)
  237 + return total, 0, 0, errors.New("webutility: unknown command: " + command)
233 238 }
234 239  
235 240 if !inited {
236   - return 0, 0, 0, errors.New("webutil: metadata not initialized but update was tried.")
  241 + return 0, 0, 0, errors.New("webutility: metadata not initialized but update was tried.")
237 242 }
238 243  
239 244 total = len(updateQue)
... ... @@ -251,44 +256,54 @@ func UpdateEntityModels(command string) (total, upd, add int, err error) {
251 256 }
252 257 }
253 258  
  259 + var uStmt *sql.Stmt
  260 + if driver == "ora" {
  261 + uStmt, err = metadataDB.Prepare("update entities set entity_model = :1 where entity_type = :2")
  262 + if err != nil {
  263 + return
  264 + }
  265 + } else if driver == "mysql" {
  266 + uStmt, err = metadataDB.Prepare("update entities set entity_model = ? where entity_type = ?")
  267 + if err != nil {
  268 + return
  269 + }
  270 + }
254 271 for _, k := range forUpdate {
255   - _, err := metadataDB.PrepAndExe(`update entities set
256   - entity_model = :1
257   - where entity_type = :2`,
258   - string(updateQue[k]),
259   - k)
260   -
  272 + _, err = uStmt.Exec(string(updateQue[k]), k)
261 273 if err != nil {
262   - logger.Log("webutility: update metadata: prep and exe: %v\n", err)
263   - continue
  274 + logger.Log("webutility: %v\n", err)
  275 + return
264 276 }
265 277 upd++
266   - logger.Log("webutility: updated %s payload model\n", k)
267 278 }
268 279  
269 280 blankPayload, _ := json.Marshal(Payload{})
  281 + var iStmt *sql.Stmt
  282 + if driver == "ora" {
  283 + iStmt, err = metadataDB.Prepare("INSERT INTO ENTITIES(PROJEKAT, METADATA, ENTITY_TYPE, ENTITY_MODEL) VALUES(:1, :2, :3, :4)")
  284 + if err != nil {
  285 + return
  286 + }
  287 + } else if driver == "mysql" {
  288 + iStmt, err = metadataDB.Prepare("INSERT INTO ENTITIES(PROJEKAT, METADATA, ENTITY_TYPE, ENTITY_MODEL) VALUES(?, ?, ?, ?)")
  289 + if err != nil {
  290 + return
  291 + }
  292 + }
270 293 for _, k := range forAdd {
271   - _, err := metadataDB.PrepAndExe(`insert into entities
272   - (projekat, metadata, entity_type, entity_model)
273   - values(:1, :2, :3, :4)`,
274   - activeProject,
275   - string(blankPayload),
276   - k,
277   - string(updateQue[k]))
278   -
  294 + _, err = iStmt.Exec(activeProject, string(blankPayload), k, string(updateQue[k]))
279 295 if err != nil {
280   - logger.Log("webutility: add metadata: prep and exe: %v\n", err)
281   - continue
  296 + logger.Log("webutility: %v\n", err)
  297 + return
282 298 }
283 299 metadata[k] = Payload{}
284 300 add++
285   - logger.Log("webutility: added %s to the payload models\n", k)
286   -
287 301 }
288 302  
289 303 return total, upd, add, nil
290 304 }
291 305  
  306 +/*
292 307 func ModifyMetadataForEntity(entityType string, p *Payload) error {
293 308 md, err := json.Marshal(*p)
294 309 if err != nil {
... ...
locale_utility.go
... ... @@ -5,9 +5,17 @@ import (
5 5 "io/ioutil"
6 6 )
7 7  
8   -var locales = map[string]map[string]string{}
  8 +type Dictionary struct {
  9 + locales map[string]map[string]string
  10 +}
  11 +
  12 +func NewDictionary() Dictionary {
  13 + return Dictionary{
  14 + locales: map[string]map[string]string{},
  15 + }
  16 +}
9 17  
10   -func LoadLocale(loc, filePath string) error {
  18 +func (d *Dictionary) AddLocale(loc, filePath string) error {
11 19 file, err := ioutil.ReadFile(filePath)
12 20 if err != nil {
13 21 return err
... ... @@ -23,11 +31,20 @@ func LoadLocale(loc, filePath string) error {
23 31 for k, v := range data.(map[string]interface{}) {
24 32 l[k] = v.(string)
25 33 }
26   - locales[loc] = l
  34 + d.locales[loc] = l
27 35  
28 36 return nil
29 37 }
30 38  
31   -func Translate(loc, key string) string {
32   - return locales[loc][key]
  39 +func (d *Dictionary) Translate(loc, key string) string {
  40 + return d.locales[loc][key]
  41 +}
  42 +
  43 +func (d *Dictionary) SupportsLocale(loc string) bool {
  44 + for k, _ := range d.locales {
  45 + if k == loc {
  46 + return true
  47 + }
  48 + }
  49 + return false
33 50 }
... ...