auth

Paddy 2015-04-11 Parent:762953f6a7f2 Child:6f473576c6ae

160:48200d8c4036 Go to Latest

auth/token_postgres.go

Start to support deleting profiles through the API. Create a removeLoginsByProfile method on the profileStore, to allow an easy way to bulk-delete logins associated with a Profile after the Profile has been deleted. Create postgres and memstore implementations of the removeLoginsByProfile method. Create a cleanUpAfterProfileDeletion helper method that will clean up the child objects of a Profile (its Sessions, Tokens, Clients, etc.). The intended usage is to call this in a goroutine after a Profile has been deleted, to try and get things back in order. Detect when the UpdateProfileHandler API is used to set the Deleted flag of a Profile to true, and clean up after the Profile when that's the case. Add a DeleteProfileHandler API endpoint that is a shortcut to setting the Deleted flag of a Profile to true and cleaning up after the Profile. The problem with our approach thus far is that some of it is reversible and some is not. If a Profile is maliciously/accidentally deleted, it's simple enough to use the API as a superuser to restore the Profile. But doing that will not (and cannot) restore the Logins associated with that Profile, for example. While it would be nice to add a Deleted flag to our Logins that we could simply toggle, that would wreak havoc with our database constraints and ensuring uniqueness of Login values. I still don't have a solution for this, outside the superuser manually restoring a Login for the Profile, after which the user can authenticate themselves and add more Logins as desired. But there has to be a better way. I suppose since the passphrase is being stored with the Profile and not the Login, we could offer an endpoint that would automate this, but... well, that would be tricky. It would require the user remembering their Profile ID, and let's be honest, nobody's going to remember a UUID. Maybe such an endpoint would help from a customer service standpoint: we identify their Profile manually, then send them to /profiles/ID/restorelogin or something, and that lets them add a Login back to the Profile. I'll figure it out later. For now, we know we at least have enough information to identify a user is who they say they are and resolve the situation manually.

History
1 package auth
3 import (
4 "code.secondbit.org/uuid.hg"
6 "github.com/lib/pq"
7 "github.com/secondbit/pan"
8 )
10 type tokenScope struct {
11 Token string
12 Scope string
13 }
15 func (t tokenScope) GetSQLTableName() string {
16 return "scopes_tokens"
17 }
19 func (t Token) GetSQLTableName() string {
20 return "tokens"
21 }
23 func (p *postgres) getTokenSQL(token string, refresh bool) *pan.Query {
24 var t Token
25 fields, _ := pan.GetFields(t)
26 query := pan.New(pan.POSTGRES, "SELECT "+pan.QueryList(fields)+" FROM "+pan.GetTableName(t))
27 query.IncludeWhere()
28 if !refresh {
29 query.Include(pan.GetUnquotedColumn(t, "AccessToken")+" = ?", token)
30 } else {
31 query.Include(pan.GetUnquotedColumn(t, "RefreshToken")+" = ?", token)
32 }
33 return query.FlushExpressions(" ")
34 }
36 func (p *postgres) getToken(token string, refresh bool) (Token, error) {
37 query := p.getTokenSQL(token, refresh)
38 rows, err := p.db.Query(query.String(), query.Args...)
39 if err != nil {
40 return Token{}, err
41 }
42 var t Token
43 var found bool
44 for rows.Next() {
45 err := pan.Unmarshal(rows, &t)
46 if err != nil {
47 return t, err
48 }
49 found = true
50 }
51 if err = rows.Err(); err != nil {
52 return t, err
53 }
54 if !found {
55 return t, ErrTokenNotFound
56 }
57 query = p.getTokenScopesSQL([]string{t.AccessToken})
58 rows, err = p.db.Query(query.String(), query.Args...)
59 if err != nil {
60 return t, err
61 }
62 for rows.Next() {
63 var ts tokenScope
64 err = pan.Unmarshal(rows, &ts)
65 if err != nil {
66 return t, err
67 }
68 t.Scopes = append(t.Scopes, ts.Scope)
69 }
70 if err = rows.Err(); err != nil {
71 return t, err
72 }
73 return t, nil
74 }
76 func (p *postgres) saveTokenSQL(token Token) *pan.Query {
77 fields, values := pan.GetFields(token)
78 query := pan.New(pan.POSTGRES, "INSERT INTO "+pan.GetTableName(token))
79 query.Include("(" + pan.QueryList(fields) + ")")
80 query.Include("VALUES")
81 query.Include("("+pan.VariableList(len(values))+")", values...)
82 return query.FlushExpressions(" ")
83 }
85 func (p *postgres) saveTokenScopesSQL(ts []tokenScope) *pan.Query {
86 fields, _ := pan.GetFields(ts[0])
87 query := pan.New(pan.POSTGRES, "INSERT INTO "+pan.GetTableName(ts[0]))
88 query.Include("(" + pan.QueryList(fields) + ")")
89 query.Include("VALUES")
90 query.FlushExpressions(" ")
91 for _, t := range ts {
92 _, values := pan.GetFields(t)
93 query.Include("("+pan.VariableList(len(values))+")", values...)
94 }
95 return query.FlushExpressions(", ")
96 }
98 func (p *postgres) saveToken(token Token) error {
99 query := p.saveTokenSQL(token)
100 _, err := p.db.Exec(query.String(), query.Args...)
101 if e, ok := err.(*pq.Error); ok && e.Constraint == "tokens_pkey" {
102 err = ErrTokenAlreadyExists
103 }
104 if err != nil || len(token.Scopes) < 1 {
105 return err
106 }
107 var ts []tokenScope
108 for _, scope := range token.Scopes {
109 ts = append(ts, tokenScope{Token: token.AccessToken, Scope: scope})
110 }
111 query = p.saveTokenScopesSQL(ts)
112 _, err = p.db.Exec(query.String(), query.Args...)
113 return err
114 }
116 func (p *postgres) revokeTokenSQL(token string, refresh bool) *pan.Query {
117 var t Token
118 query := pan.New(pan.POSTGRES, "UPDATE "+pan.GetTableName(t)+" SET ")
119 query.Include(pan.GetUnquotedColumn(t, "Revoked")+" = ?", true)
120 query.IncludeWhere()
121 if !refresh {
122 query.Include(pan.GetUnquotedColumn(t, "AccessToken")+" = ?", token)
123 } else {
124 query.Include(pan.GetUnquotedColumn(t, "RefreshToken")+" = ?", token)
125 }
126 return query.FlushExpressions(" ")
127 }
129 func (p *postgres) revokeToken(token string, refresh bool) error {
130 query := p.revokeTokenSQL(token, refresh)
131 res, err := p.db.Exec(query.String(), query.Args...)
132 if err != nil {
133 return err
134 }
135 rows, err := res.RowsAffected()
136 if err != nil {
137 return err
138 }
139 if rows == 0 {
140 return ErrTokenNotFound
141 }
142 return nil
143 }
145 func (p *postgres) getTokensByProfileIDSQL(profileID uuid.ID, num, offset int) *pan.Query {
146 var token Token
147 fields, _ := pan.GetFields(token)
148 query := pan.New(pan.POSTGRES, "SELECT "+pan.QueryList(fields)+" FROM "+pan.GetTableName(token))
149 query.IncludeWhere()
150 query.Include(pan.GetUnquotedColumn(token, "ProfileID")+" = ?", profileID)
151 query.IncludeLimit(int64(num))
152 query.IncludeOffset(int64(offset))
153 return query.FlushExpressions(" ")
154 }
156 func (p *postgres) getTokenScopesSQL(tokens []string) *pan.Query {
157 var t tokenScope
158 fields, _ := pan.GetFields(t)
159 tokensI := make([]interface{}, len(tokens))
160 for pos, token := range tokens {
161 tokensI[pos] = token
162 }
163 query := pan.New(pan.POSTGRES, "SELECT "+pan.QueryList(fields)+" FROM "+pan.GetTableName(t))
164 query.IncludeWhere()
165 query.Include(pan.GetUnquotedColumn(t, "Token")+" IN ("+pan.VariableList(len(tokensI))+")", tokensI...)
166 return query.FlushExpressions(" ")
167 }
169 func (p *postgres) getTokensByProfileID(profileID uuid.ID, num, offset int) ([]Token, error) {
170 query := p.getTokensByProfileIDSQL(profileID, num, offset)
171 rows, err := p.db.Query(query.String(), query.Args...)
172 if err != nil {
173 return []Token{}, err
174 }
175 var tokens []Token
176 var tokenIDs []string
177 for rows.Next() {
178 var token Token
179 err = pan.Unmarshal(rows, &token)
180 if err != nil {
181 return tokens, err
182 }
183 tokens = append(tokens, token)
184 tokenIDs = append(tokenIDs, token.AccessToken)
185 }
186 if err = rows.Err(); err != nil {
187 return tokens, err
188 }
189 if len(tokenIDs) < 1 {
190 return tokens, nil
191 }
192 scopes := map[string][]string{}
193 query = p.getTokenScopesSQL(tokenIDs)
194 rows, err = p.db.Query(query.String(), query.Args...)
195 if err != nil {
196 return tokens, err
197 }
198 for rows.Next() {
199 var t tokenScope
200 err = pan.Unmarshal(rows, &t)
201 if err != nil {
202 return tokens, err
203 }
204 scopes[t.Token] = append(scopes[t.Token], t.Scope)
205 }
206 if err = rows.Err(); err != nil {
207 return tokens, err
208 }
209 for pos, token := range tokens {
210 token.Scopes = scopes[token.AccessToken]
211 tokens[pos] = token
212 }
213 return tokens, nil
214 }