This repository has been archived by the owner on Nov 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.go
114 lines (91 loc) · 2.37 KB
/
app.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
package data
import (
"fmt"
"strings"
"time"
"upper.io/db.v2"
"upper.io/db.v2/lib/sqlbuilder"
)
type App struct {
ID int64 `db:"id,omitempty,pk" json:"id"`
Name string `db:"name,omitempty" json:"name"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
}
func (a App) CollectionName() string {
return "apps"
}
func (a App) Query(session db.Database, query db.Cond) db.Result {
return session.Collection(a.CollectionName()).Find(query)
}
func (a *App) Find(session db.Database, query db.Cond) error {
return a.Query(session, query).One(a)
}
func (a *App) Load(session db.Database) error {
if session == nil {
session = dbSession
}
return a.Query(session, db.Cond{"id": a.ID}).One(a)
}
func (a *App) Save(session db.Database) error {
if session == nil {
session = dbSession
}
collection := session.Collection(a.CollectionName())
var err error
if a.ID == 0 {
var id interface{}
a.UpdatedAt = time.Now().UTC().Truncate(time.Second)
a.CreatedAt = a.UpdatedAt
id, err = collection.Insert(a)
if err == nil {
a.ID = id.(int64)
}
} else {
a.UpdatedAt = time.Now().UTC().Truncate(time.Second)
err = collection.
Find(db.Cond{"id": a.ID}).
Update(a)
}
return err
}
func (a *App) Remove(session db.Database) error {
return a.Query(session, db.Cond{"id": a.ID}).Delete()
}
// SearchAppsByName returns the list of find apps under that user's permission
func SearchAppsByName(userID int64, name string) []*App {
name = strings.ToLower(name)
sql := fmt.Sprintf(`
SELECT apps.id, apps.name, apps.updated_at, apps.created_at
FROM apps
JOIN permissions
ON apps.id=permissions.app_id
WHERE permissions.user_id=%d AND lower(apps.name) LIKE '%%%s%%'`, userID, name)
rows, err := dbSession.Query(sql)
if err != nil {
return nil
}
var apps []*App
iter := sqlbuilder.NewIterator(rows)
iter.All(&apps)
return apps
}
func FindAppByUserIDAppID(userID, appID int64) *App {
sql := fmt.Sprintf(`
SELECT apps.id, apps.name, apps.updated_at, apps.created_at
FROM apps
JOIN permissions
ON apps.id=permissions.app_id
WHERE permissions.user_id=%d AND apps.id=%d`, userID, appID)
rows, err := dbSession.Query(sql)
if err != nil {
return nil
}
var apps []*App
iter := sqlbuilder.NewIterator(rows)
iter.All(&apps)
if len(apps) == 1 {
return apps[0]
}
return nil
}