/
access.go
131 lines (102 loc) · 2.66 KB
/
access.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
package models
import (
"github.com/asaskevich/govalidator"
"github.com/gotoolz/errors"
"github.com/gotoolz/validator"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"time"
)
type accessMapper struct{}
var AccessMapper = &accessMapper{}
const accessCollection = "access"
func init() {
col := C(accessCollection)
defer col.Database.Session.Close()
// Name Index
col.EnsureIndex(mgo.Index{
Key: []string{"type"},
Unique: true,
DropDups: true,
Background: true, // See notes.
Sparse: true,
})
govalidator.TagMap["access_provider"] = govalidator.Validator(func(str string) bool {
if str == "ec2" || str == "do" {
return true
}
return false
})
}
type Access struct {
Id bson.ObjectId `json:"id" bson:"_id"`
Type string `json:"type" bson:"type"`
AccessKey string `json:"access_key" bson:"access_key"`
PrivateKey string `json:"-" bson:"private_key"`
CreatedAt time.Time `json:"created_at" bson:"created_at"`
}
type Accesses []*Access
// AlertGroup creation form
type AccessCreateForm struct {
Type string `json:"type" form:"type" valid:"access_provider,required"`
AccessKey string `json:"access_key" form:"access_key" valid:"required"`
PrivateKey string `json:"private_key" form:"private_key" valid:"-"`
}
// Validator for application creation
func (f AccessCreateForm) Validate() *errors.Errors {
if errs := validator.Validate(&f); errs != nil {
return errs
}
a, err := AccessMapper.FetchOne(f.Type)
if err != nil {
panic(err)
}
if a != nil {
return errors.New(errors.Error{
Label: "duplicate_type",
Field: "type",
Text: "Duplicate access type: " + f.Type,
})
}
return nil
}
func (am *accessMapper) Create(f *AccessCreateForm) *Access {
return &Access{
Id: bson.NewObjectId(),
Type: f.Type,
AccessKey: f.AccessKey,
PrivateKey: f.PrivateKey,
CreatedAt: time.Now(),
}
}
func (pm *accessMapper) Save(a *Access) error {
col := C(accessCollection)
defer col.Database.Session.Close()
return col.Insert(a)
}
// func (pm *accessMapper) Update(a *Access) error {
//
// col := C(accessCollection)
// defer col.Database.Session.Close()
//
// ag.UpdatedAt = time.Now()
//
// return col.UpdateId(ag.Id, ag)
// }
func (pm *accessMapper) Delete(a *Access) error {
col := C(accessCollection)
defer col.Database.Session.Close()
return col.RemoveId(a.Id)
}
func (am *accessMapper) FetchOne(typ string) (*Access, error) {
col := C(accessCollection)
defer col.Database.Session.Close()
a := new(Access)
if err := col.Find(bson.M{"type": typ}).One(a); err != nil {
if err == mgo.ErrNotFound {
return nil, nil
}
return nil, err
}
return a, nil
}