earaujoassis / space
1
package models
2

3
import (
4
    "time"
5
    "math/rand"
6

7
    "github.com/satori/go.uuid"
8
    "gopkg.in/bluesuncorp/validator.v5"
9

10
    "github.com/earaujoassis/space/config"
11
)
12

13
// Model is the base model/struct for any model in the application/system
14
type Model struct {
15
    ID uint                     `gorm:"primary_key" json:"-"`
16
    CreatedAt time.Time         `gorm:"not null" json:"-"`
17
    UpdatedAt time.Time         `json:"-"`
18
}
19

20
const (
21
    letterBytes   = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
22
    letterIdxBits = 6                    // 6 bits to represent a letter index
23
    letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
24
    letterIdxMax  = 63 / letterIdxBits   // # of letter indices fitting in 63 bits
25
)
26

27
var src = rand.NewSource(time.Now().UnixNano())
28

29
// GenerateRandomString returns a random string with `n` as the length
30 1
func GenerateRandomString(n int) string {
31 1
    b := make([]byte, n)
32 1
    for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
33 1
        if remain == 0 {
34 1
            cache, remain = src.Int63(), letterIdxMax
35
        }
36 1
        if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
37 1
            b[i] = letterBytes[idx]
38 1
            i--
39
        }
40 1
        cache >>= letterIdxBits
41 1
        remain--
42
    }
43

44 1
    return string(b)
45
}
46

47 0
func generateUUID() string {
48 0
    return uuid.NewV4().String()
49
}
50

51 1
func validateModel(tagName string, model interface{}) error {
52 1
    validate := validator.New(tagName, validator.BakedInValidators)
53 1
    validate.AddFunction("client", validClientType)
54 1
    validate.AddFunction("scope", validScope)
55 1
    validate.AddFunction("restrict", validClientScopes)
56 1
    validate.AddFunction("token", validTokenType)
57 1
    validate.AddFunction("canonical", validCanonicalURIs)
58 1
    validate.AddFunction("redirect", validRedirectURIs)
59 1
    validate.AddFunction("action", validAction)
60 1
    err := validate.Struct(model)
61 1
    if err != nil {
62 1
        return err
63
    }
64 1
    return nil
65
}
66

67
// IsValid checks if a `model` entry is valid, given the `tagName` (scope) for validation
68 1
func IsValid(tagName string, model interface{}) bool {
69 1
    err := validateModel(tagName, model)
70 1
    if err != nil {
71 1
        return false
72
    }
73 1
    return true
74
}
75

76 0
func defaultKey() []byte {
77 0
    keyString := config.GetGlobalConfig().StorageSecret
78 0
    return []byte(keyString)
79
}

Read our documentation on viewing source code .

Loading