forked from tsuru/tsuru
-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
99 lines (85 loc) · 2.17 KB
/
token.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
// Copyright 2014 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package oauth
import (
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/tsuru/config"
"github.com/tsuru/tsuru/auth"
"github.com/tsuru/tsuru/db"
"github.com/tsuru/tsuru/db/storage"
"github.com/tsuru/tsuru/log"
"github.com/tsuru/tsuru/permission"
authTypes "github.com/tsuru/tsuru/types/auth"
"golang.org/x/oauth2"
)
type Token struct {
oauth2.Token
UserEmail string `json:"email"`
}
func (t *Token) GetValue() string {
return t.AccessToken
}
func (t *Token) User() (*authTypes.User, error) {
return auth.ConvertOldUser(auth.GetUserByEmail(t.UserEmail))
}
func (t *Token) IsAppToken() bool {
return false
}
func (t *Token) GetUserName() string {
return t.UserEmail
}
func (t *Token) GetAppName() string {
return ""
}
func (t *Token) Permissions() ([]permission.Permission, error) {
return auth.BaseTokenPermission(t)
}
func getToken(header string) (*Token, error) {
var t Token
token, err := auth.ParseToken(header)
if err != nil {
return nil, err
}
coll := collection()
defer coll.Close()
err = coll.Find(bson.M{"token.accesstoken": token}).One(&t)
if err != nil {
if err == mgo.ErrNotFound {
return nil, auth.ErrInvalidToken
}
return nil, err
}
return &t, nil
}
func deleteToken(token string) error {
coll := collection()
defer coll.Close()
return coll.Remove(bson.M{"token.accesstoken": token})
}
func deleteAllTokens(email string) error {
coll := collection()
defer coll.Close()
_, err := coll.RemoveAll(bson.M{"useremail": email})
return err
}
func (t *Token) save() error {
coll := collection()
defer coll.Close()
return coll.Insert(t)
}
func collection() *storage.Collection {
name, err := config.GetString("auth:oauth:collection")
if err != nil {
name = "oauth_tokens"
log.Debugf("auth:oauth:collection not found using default value: %s.", name)
}
conn, err := db.Conn()
if err != nil {
log.Errorf("Failed to connect to the database: %s", err)
}
coll := conn.Collection(name)
coll.EnsureIndex(mgo.Index{Key: []string{"token.accesstoken"}})
return coll
}