This repository has been archived by the owner on Jul 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
key.go
75 lines (62 loc) · 1.86 KB
/
key.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
package models
import (
"gofreta/app"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/globalsign/mgo/bson"
"github.com/go-ozzo/ozzo-routing/auth"
validation "github.com/go-ozzo/ozzo-validation"
)
type (
// Key defines the API Key model fields.
Key struct {
ID bson.ObjectId `json:"id" bson:"_id"`
Title string `json:"title" bson:"title"`
Token string `json:"token" bson:"token"`
Access map[string][]string `json:"access" bson:"access"`
Created int64 `json:"created" bson:"created"`
Modified int64 `json:"modified" bson:"modified"`
}
// KeyForm defines the update/create form model fields.
KeyForm struct {
Model *Key `json:"-" form:"-"`
Title string `json:"title" form:"title"`
Access map[string][]string `json:"access" form:"access"`
}
)
// NewAuthToken generates and returns new api key authentication token.
func (m Key) NewAuthToken(exp int64) (string, error) {
claims := jwt.MapClaims{
"id": m.ID.Hex(),
"model": "key",
"exp": exp,
}
signingKey := app.Config.GetString("jwt.signingKey")
return auth.NewJWT(claims, signingKey)
}
// Validate validates the KeyForm struct fields.
func (m KeyForm) Validate() error {
return validation.ValidateStruct(&m,
validation.Field(&m.Title, validation.Required),
validation.Field(&m.Access, validation.Required),
)
}
// ResolveModel resolves and returns the form Key model.
// If the form doesn't have a Key model, it will instantiate a new one.
func (m KeyForm) ResolveModel() *Key {
var model Key
now := time.Now().Unix()
// is new
if m.Model == nil {
model = Key{}
model.ID = bson.NewObjectId()
model.Created = now
model.Token, _ = model.NewAuthToken(0)
} else {
model = *m.Model
}
model.Title = m.Title
model.Access = m.Access
model.Modified = now
return &model
}