auth

Paddy 2015-03-22 Parent:379702564771 Child:de5e09680f6b

151:77db7c65216c Browse Files

Implement postgres clientStore. Stop requiring the client ID be passed to clientStore.addEndpoints and context.AddEndpoints. The Endpoints themselves contain the client ID. When using the authd server, set the log flags to include the file path and line number. Add an ErrEndpointAlreadyExists error, to return when creating an endpoint and its ID already exists in the database. Add a Deleted property to Clients and remove the clientStore.deleteClient and context.DeleteClient methods. We're not going to actually remove that data, and we want to be able to restore it, so include it in the ClientChange type and call it using UpdateClient. Create a ClientChange.Empty helper method that will return whether the ClientChange has any changes to perform. Return ErrClientNotFound from clientStore.getClient if the Client's Deleted property is set to true. This also requires us to ignore ErrClientNotFound errors when calling memstore.listClientsByOwner, as they should just be skipped instead of returning an error. Add the postgres type methods needed to implement clientStore. Include postgres as a clientStore if the testing.Short() flag is not set. Generate a new ID for the Client on every run in the tests, now that we can't actually remove it from the database/memstore in code. We really just need a *Store.Reset() function that erases all the data and starts over again, to give the tests a clean execution environment (and so they can clean up after themselves). Add the CREATE TABLE statements for the Clients table and the Endpoints table to sql/postgres_init.sql.

authcode_test.go authd/server.go client.go client_postgres.go client_test.go context.go oauth2_test.go sql/postgres_init.sql

     1.1 --- a/authcode_test.go	Sat Mar 21 18:46:57 2015 -0400
     1.2 +++ b/authcode_test.go	Sun Mar 22 16:26:37 2015 -0400
     1.3 @@ -141,7 +141,7 @@
     1.4  	if err != nil {
     1.5  		t.Fatal("Can't store client:", err)
     1.6  	}
     1.7 -	err = testContext.AddEndpoints(client.ID, []Endpoint{endpoint})
     1.8 +	err = testContext.AddEndpoints([]Endpoint{endpoint})
     1.9  	if err != nil {
    1.10  		t.Fatal("Can't store endpoint:", err)
    1.11  	}
     2.1 --- a/authd/server.go	Sat Mar 21 18:46:57 2015 -0400
     2.2 +++ b/authd/server.go	Sun Mar 22 16:26:37 2015 -0400
     2.3 @@ -10,6 +10,7 @@
     2.4  )
     2.5  
     2.6  func main() {
     2.7 +	log.SetFlags(log.LstdFlags | log.Llongfile)
     2.8  	p, err := auth.NewPostgres("dbname=testdb sslmode=disable")
     2.9  	if err != nil {
    2.10  		panic(err)
    2.11 @@ -19,7 +20,7 @@
    2.12  		panic(err)
    2.13  	}
    2.14  	config := auth.Config{
    2.15 -		ClientStore:   store,
    2.16 +		ClientStore:   &p,
    2.17  		AuthCodeStore: store,
    2.18  		ProfileStore:  &p,
    2.19  		TokenStore:    store,
     3.1 --- a/client.go	Sat Mar 21 18:46:57 2015 -0400
     3.2 +++ b/client.go	Sun Mar 22 16:26:37 2015 -0400
     3.3 @@ -39,6 +39,9 @@
     3.4  	ErrClientAlreadyExists = errors.New("client already exists in clientStore")
     3.5  	// ErrEndpointNotFound is returned when an Endpoint is requested but not found in a clientSTore.
     3.6  	ErrEndpointNotFound = errors.New("endpoint not found in clientStore")
     3.7 +	// ErrEndpointAlreadyExists is returned when an Endpoint is added to a clientStore, but another Endpoint
     3.8 +	// with the same ID already exists in the clientStore.
     3.9 +	ErrEndpointAlreadyExists = errors.New("endpoint already exists in clientStore")
    3.10  
    3.11  	// ErrEmptyChange is returned when a Change has all its properties set to nil.
    3.12  	ErrEmptyChange = errors.New("change must have at least one property set")
    3.13 @@ -82,6 +85,7 @@
    3.14  	Logo    string  `json:"logo,omitempty"`
    3.15  	Website string  `json:"website,omitempty"`
    3.16  	Type    string  `json:"type,omitempty"`
    3.17 +	Deleted bool    `json:"deleted,omitempty"`
    3.18  }
    3.19  
    3.20  // ApplyChange applies the properties of the passed
    3.21 @@ -102,6 +106,9 @@
    3.22  	if change.Website != nil {
    3.23  		c.Website = *change.Website
    3.24  	}
    3.25 +	if change.Deleted != nil {
    3.26 +		c.Deleted = *change.Deleted
    3.27 +	}
    3.28  }
    3.29  
    3.30  // ClientChange represents a bundle of options for
    3.31 @@ -112,13 +119,18 @@
    3.32  	Name    *string
    3.33  	Logo    *string
    3.34  	Website *string
    3.35 +	Deleted *bool
    3.36 +}
    3.37 +
    3.38 +func (c ClientChange) Empty() bool {
    3.39 +	return c.Secret == nil && c.OwnerID == nil && c.Name == nil && c.Logo == nil && c.Website == nil && c.Deleted == nil
    3.40  }
    3.41  
    3.42  // Validate checks the ClientChange it is called on
    3.43  // and asserts its internal validity, or lack thereof.
    3.44  func (c ClientChange) Validate() []error {
    3.45  	errors := []error{}
    3.46 -	if c.Secret == nil && c.OwnerID == nil && c.Name == nil && c.Logo == nil && c.Website == nil {
    3.47 +	if c.Empty() {
    3.48  		errors = append(errors, ErrEmptyChange)
    3.49  		return errors
    3.50  	}
    3.51 @@ -255,10 +267,9 @@
    3.52  	getClient(id uuid.ID) (Client, error)
    3.53  	saveClient(client Client) error
    3.54  	updateClient(id uuid.ID, change ClientChange) error
    3.55 -	deleteClient(id uuid.ID) error
    3.56  	listClientsByOwner(ownerID uuid.ID, num, offset int) ([]Client, error)
    3.57  
    3.58 -	addEndpoints(client uuid.ID, endpoint []Endpoint) error
    3.59 +	addEndpoints(endpoint []Endpoint) error
    3.60  	removeEndpoint(client, endpoint uuid.ID) error
    3.61  	getEndpoint(client, endpoint uuid.ID) (Endpoint, error)
    3.62  	checkEndpoint(client uuid.ID, endpoint string) (bool, error)
    3.63 @@ -270,7 +281,7 @@
    3.64  	m.clientLock.RLock()
    3.65  	defer m.clientLock.RUnlock()
    3.66  	c, ok := m.clients[id.String()]
    3.67 -	if !ok {
    3.68 +	if !ok || c.Deleted {
    3.69  		return Client{}, ErrClientNotFound
    3.70  	}
    3.71  	return c, nil
    3.72 @@ -299,27 +310,6 @@
    3.73  	return nil
    3.74  }
    3.75  
    3.76 -func (m *memstore) deleteClient(id uuid.ID) error {
    3.77 -	client, err := m.getClient(id)
    3.78 -	if err != nil {
    3.79 -		return err
    3.80 -	}
    3.81 -	m.clientLock.Lock()
    3.82 -	defer m.clientLock.Unlock()
    3.83 -	delete(m.clients, id.String())
    3.84 -	pos := -1
    3.85 -	for p, item := range m.profileClientLookup[client.OwnerID.String()] {
    3.86 -		if item.Equal(id) {
    3.87 -			pos = p
    3.88 -			break
    3.89 -		}
    3.90 -	}
    3.91 -	if pos >= 0 {
    3.92 -		m.profileClientLookup[client.OwnerID.String()] = append(m.profileClientLookup[client.OwnerID.String()][:pos], m.profileClientLookup[client.OwnerID.String()][pos+1:]...)
    3.93 -	}
    3.94 -	return nil
    3.95 -}
    3.96 -
    3.97  func (m *memstore) listClientsByOwner(ownerID uuid.ID, num, offset int) ([]Client, error) {
    3.98  	ids := m.lookupClientsByProfileID(ownerID.String())
    3.99  	if len(ids) > num+offset {
   3.100 @@ -333,6 +323,9 @@
   3.101  	for _, id := range ids {
   3.102  		client, err := m.getClient(id)
   3.103  		if err != nil {
   3.104 +			if err == ErrClientNotFound {
   3.105 +				continue
   3.106 +			}
   3.107  			return []Client{}, err
   3.108  		}
   3.109  		clients = append(clients, client)
   3.110 @@ -340,10 +333,16 @@
   3.111  	return clients, nil
   3.112  }
   3.113  
   3.114 -func (m *memstore) addEndpoints(client uuid.ID, endpoints []Endpoint) error {
   3.115 +func (m *memstore) addEndpoints(endpoints []Endpoint) error {
   3.116  	m.endpointLock.Lock()
   3.117  	defer m.endpointLock.Unlock()
   3.118 -	m.endpoints[client.String()] = append(m.endpoints[client.String()], endpoints...)
   3.119 +	clients := map[string][]Endpoint{}
   3.120 +	for _, endpoint := range endpoints {
   3.121 +		clients[endpoint.ClientID.String()] = append(clients[endpoint.ClientID.String()], endpoint)
   3.122 +	}
   3.123 +	for client, e := range clients {
   3.124 +		m.endpoints[client] = append(m.endpoints[client], e...)
   3.125 +	}
   3.126  	return nil
   3.127  }
   3.128  
   3.129 @@ -507,7 +506,7 @@
   3.130  		}
   3.131  		endpoints = append(endpoints, endpoint)
   3.132  	}
   3.133 -	err = c.AddEndpoints(client.ID, endpoints)
   3.134 +	err = c.AddEndpoints(endpoints)
   3.135  	if err != nil {
   3.136  		log.Printf("Error adding endpoints: %#+v\n", err)
   3.137  		errors = append(errors, requestError{Slug: requestErrActOfGod})
   3.138 @@ -793,7 +792,9 @@
   3.139  		encode(w, r, http.StatusForbidden, response{Errors: errors})
   3.140  		return
   3.141  	}
   3.142 -	err = c.DeleteClient(id)
   3.143 +	deleted := true
   3.144 +	change := ClientChange{Deleted: &deleted}
   3.145 +	err = c.UpdateClient(id, change)
   3.146  	if err != nil {
   3.147  		if err == ErrClientNotFound {
   3.148  			errors = append(errors, requestError{Slug: requestErrNotFound})
   3.149 @@ -893,7 +894,7 @@
   3.150  		encode(w, r, http.StatusBadRequest, response{Errors: errors})
   3.151  		return
   3.152  	}
   3.153 -	err = c.AddEndpoints(id, endpoints)
   3.154 +	err = c.AddEndpoints(endpoints)
   3.155  	if err != nil {
   3.156  		encode(w, r, http.StatusInternalServerError, actOfGodResponse)
   3.157  		return
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/client_postgres.go	Sun Mar 22 16:26:37 2015 -0400
     4.3 @@ -0,0 +1,292 @@
     4.4 +package auth
     4.5 +
     4.6 +import (
     4.7 +	"code.secondbit.org/uuid.hg"
     4.8 +	"github.com/lib/pq"
     4.9 +	"github.com/secondbit/pan"
    4.10 +)
    4.11 +
    4.12 +func (c Client) GetSQLTableName() string {
    4.13 +	return "clients"
    4.14 +}
    4.15 +
    4.16 +func (e Endpoint) GetSQLTableName() string {
    4.17 +	return "endpoints"
    4.18 +}
    4.19 +
    4.20 +func (p *postgres) getClientSQL(id uuid.ID) *pan.Query {
    4.21 +	var client Client
    4.22 +	fields, _ := pan.GetFields(client)
    4.23 +	query := pan.New(pan.POSTGRES, "SELECT "+pan.QueryList(fields)+" FROM "+pan.GetTableName(client))
    4.24 +	query.IncludeWhere()
    4.25 +	query.Include(pan.GetUnquotedColumn(client, "ID")+" = ? AND "+pan.GetUnquotedColumn(client, "Deleted")+" = ?", id, false)
    4.26 +	return query.FlushExpressions(" ")
    4.27 +}
    4.28 +
    4.29 +func (p *postgres) getClient(id uuid.ID) (Client, error) {
    4.30 +	query := p.getClientSQL(id)
    4.31 +	rows, err := p.db.Query(query.String(), query.Args...)
    4.32 +	if err != nil {
    4.33 +		return Client{}, err
    4.34 +	}
    4.35 +	var client Client
    4.36 +	var found bool
    4.37 +	for rows.Next() {
    4.38 +		err := pan.Unmarshal(rows, &client)
    4.39 +		if err != nil {
    4.40 +			return client, err
    4.41 +		}
    4.42 +		found = true
    4.43 +	}
    4.44 +	if err = rows.Err(); err != nil {
    4.45 +		return client, err
    4.46 +	}
    4.47 +	if !found {
    4.48 +		return client, ErrClientNotFound
    4.49 +	}
    4.50 +	return client, nil
    4.51 +}
    4.52 +
    4.53 +func (p *postgres) saveClientSQL(client Client) *pan.Query {
    4.54 +	fields, values := pan.GetFields(client)
    4.55 +	query := pan.New(pan.POSTGRES, "INSERT INTO "+pan.GetTableName(client))
    4.56 +	query.Include("(" + pan.QueryList(fields) + ")")
    4.57 +	query.Include("VALUES")
    4.58 +	query.Include("("+pan.VariableList(len(values))+")", values...)
    4.59 +	return query.FlushExpressions(" ")
    4.60 +}
    4.61 +
    4.62 +func (p *postgres) saveClient(client Client) error {
    4.63 +	query := p.saveClientSQL(client)
    4.64 +	_, err := p.db.Exec(query.String(), query.Args...)
    4.65 +	if e, ok := err.(*pq.Error); ok && e.Constraint == "clients_pkey" {
    4.66 +		err = ErrClientAlreadyExists
    4.67 +	}
    4.68 +	return err
    4.69 +}
    4.70 +
    4.71 +func (p *postgres) updateClientSQL(id uuid.ID, change ClientChange) *pan.Query {
    4.72 +	var client Client
    4.73 +	query := pan.New(pan.POSTGRES, "UPDATE "+pan.GetTableName(client)+" SET ")
    4.74 +	query.IncludeIfNotNil(pan.GetUnquotedColumn(client, "Secret")+" = ?", change.Secret)
    4.75 +	query.IncludeIfNotNil(pan.GetUnquotedColumn(client, "OwnerID")+" = ?", change.OwnerID)
    4.76 +	query.IncludeIfNotNil(pan.GetUnquotedColumn(client, "Name")+" = ?", change.Name)
    4.77 +	query.IncludeIfNotNil(pan.GetUnquotedColumn(client, "Logo")+" = ?", change.Logo)
    4.78 +	query.IncludeIfNotNil(pan.GetUnquotedColumn(client, "Website")+" = ?", change.Website)
    4.79 +	query.IncludeIfNotNil(pan.GetUnquotedColumn(client, "Deleted")+" = ?", change.Deleted)
    4.80 +	query.FlushExpressions(", ")
    4.81 +	query.IncludeWhere()
    4.82 +	query.Include(pan.GetUnquotedColumn(client, "ID")+" = ?", id)
    4.83 +	return query.FlushExpressions(" ")
    4.84 +}
    4.85 +
    4.86 +func (p *postgres) updateClient(id uuid.ID, change ClientChange) error {
    4.87 +	if change.Empty() {
    4.88 +		return nil
    4.89 +	}
    4.90 +	query := p.updateClientSQL(id, change)
    4.91 +	_, err := p.db.Exec(query.String(), query.Args...)
    4.92 +	return err
    4.93 +}
    4.94 +
    4.95 +func (p *postgres) listClientsByOwnerSQL(ownerID uuid.ID, num, offset int) *pan.Query {
    4.96 +	var client Client
    4.97 +	fields, _ := pan.GetFields(client)
    4.98 +	query := pan.New(pan.POSTGRES, "SELECT "+pan.QueryList(fields)+" FROM "+pan.GetTableName(client))
    4.99 +	query.IncludeWhere()
   4.100 +	query.Include(pan.GetUnquotedColumn(client, "OwnerID")+" = ? AND "+pan.GetUnquotedColumn(client, "Deleted")+" = ?", ownerID, false)
   4.101 +	query.IncludeLimit(int64(num))
   4.102 +	query.IncludeOffset(int64(offset))
   4.103 +	return query.FlushExpressions(" ")
   4.104 +}
   4.105 +
   4.106 +func (p *postgres) listClientsByOwner(ownerID uuid.ID, num, offset int) ([]Client, error) {
   4.107 +	query := p.listClientsByOwnerSQL(ownerID, num, offset)
   4.108 +	rows, err := p.db.Query(query.String(), query.Args...)
   4.109 +	if err != nil {
   4.110 +		return []Client{}, err
   4.111 +	}
   4.112 +	var clients []Client
   4.113 +	for rows.Next() {
   4.114 +		var client Client
   4.115 +		err = pan.Unmarshal(rows, &client)
   4.116 +		if err != nil {
   4.117 +			return clients, err
   4.118 +		}
   4.119 +		clients = append(clients, client)
   4.120 +	}
   4.121 +	if err = rows.Err(); err != nil {
   4.122 +		return clients, err
   4.123 +	}
   4.124 +	return clients, nil
   4.125 +}
   4.126 +
   4.127 +func (p *postgres) addEndpointsSQL(endpoints []Endpoint) *pan.Query {
   4.128 +	fields, _ := pan.GetFields(endpoints[0])
   4.129 +	query := pan.New(pan.POSTGRES, "INSERT INTO "+pan.GetTableName(endpoints[0]))
   4.130 +	query.Include("(" + pan.QueryList(fields) + ")")
   4.131 +	query.Include("VALUES")
   4.132 +	query.FlushExpressions(" ")
   4.133 +	for _, endpoint := range endpoints {
   4.134 +		_, values := pan.GetFields(endpoint)
   4.135 +		query.Include("("+pan.VariableList(len(values))+")", values...)
   4.136 +	}
   4.137 +	return query.FlushExpressions(", ")
   4.138 +}
   4.139 +
   4.140 +func (p *postgres) addEndpoints(endpoints []Endpoint) error {
   4.141 +	if len(endpoints) < 1 {
   4.142 +		return nil
   4.143 +	}
   4.144 +	query := p.addEndpointsSQL(endpoints)
   4.145 +	_, err := p.db.Exec(query.String(), query.Args...)
   4.146 +	if e, ok := err.(*pq.Error); ok && e.Constraint == "endpoints_pkey" {
   4.147 +		return ErrEndpointAlreadyExists
   4.148 +	}
   4.149 +	return err
   4.150 +}
   4.151 +
   4.152 +func (p *postgres) removeEndpointSQL(client, endpoint uuid.ID) *pan.Query {
   4.153 +	var e Endpoint
   4.154 +	query := pan.New(pan.POSTGRES, "DELETE FROM "+pan.GetTableName(e))
   4.155 +	query.IncludeWhere()
   4.156 +	query.Include(pan.GetUnquotedColumn(e, "ID")+" = ? AND "+pan.GetUnquotedColumn(e, "ClientID")+" = ?", endpoint, client)
   4.157 +	return query.FlushExpressions(" ")
   4.158 +}
   4.159 +
   4.160 +func (p *postgres) removeEndpoint(client, endpoint uuid.ID) error {
   4.161 +	query := p.removeEndpointSQL(client, endpoint)
   4.162 +	res, err := p.db.Exec(query.String(), query.Args...)
   4.163 +	if err != nil {
   4.164 +		return err
   4.165 +	}
   4.166 +	rows, err := res.RowsAffected()
   4.167 +	if err != nil {
   4.168 +		return err
   4.169 +	}
   4.170 +	if rows == 0 {
   4.171 +		return ErrEndpointNotFound
   4.172 +	}
   4.173 +	return nil
   4.174 +}
   4.175 +
   4.176 +func (p *postgres) getEndpointSQL(client, endpoint uuid.ID) *pan.Query {
   4.177 +	var e Endpoint
   4.178 +	fields, _ := pan.GetFields(e)
   4.179 +	query := pan.New(pan.POSTGRES, "SELECT "+pan.QueryList(fields)+" FROM "+pan.GetTableName(e))
   4.180 +	query.IncludeWhere()
   4.181 +	query.FlushExpressions(" ")
   4.182 +	query.Include(pan.GetUnquotedColumn(e, "ID")+" = ?", endpoint)
   4.183 +	query.Include(pan.GetUnquotedColumn(e, "ClientID")+" = ?", client)
   4.184 +	return query.FlushExpressions(" AND ")
   4.185 +}
   4.186 +
   4.187 +func (p *postgres) getEndpoint(client, endpoint uuid.ID) (Endpoint, error) {
   4.188 +	query := p.getEndpointSQL(client, endpoint)
   4.189 +	rows, err := p.db.Query(query.String(), query.Args...)
   4.190 +	if err != nil {
   4.191 +		return Endpoint{}, err
   4.192 +	}
   4.193 +	var e Endpoint
   4.194 +	var found bool
   4.195 +	for rows.Next() {
   4.196 +		err := pan.Unmarshal(rows, &e)
   4.197 +		if err != nil {
   4.198 +			return e, err
   4.199 +		}
   4.200 +		found = true
   4.201 +	}
   4.202 +	if err = rows.Err(); err != nil {
   4.203 +		return e, err
   4.204 +	}
   4.205 +	if !found {
   4.206 +		return e, ErrEndpointNotFound
   4.207 +	}
   4.208 +	return e, nil
   4.209 +}
   4.210 +
   4.211 +func (p *postgres) checkEndpointSQL(client uuid.ID, endpoint string) *pan.Query {
   4.212 +	var e Endpoint
   4.213 +	fields, _ := pan.GetFields(e)
   4.214 +	query := pan.New(pan.POSTGRES, "SELECT "+pan.QueryList(fields)+" FROM "+pan.GetTableName(e))
   4.215 +	query.IncludeWhere()
   4.216 +	query.FlushExpressions(" ")
   4.217 +	query.Include(pan.GetUnquotedColumn(e, "ClientID")+" = ?", client)
   4.218 +	query.Include(pan.GetUnquotedColumn(e, "NormalizedURI")+" = ?", endpoint)
   4.219 +	return query.FlushExpressions(" AND ")
   4.220 +}
   4.221 +
   4.222 +func (p *postgres) checkEndpoint(client uuid.ID, endpoint string) (bool, error) {
   4.223 +	query := p.checkEndpointSQL(client, endpoint)
   4.224 +	rows, err := p.db.Query(query.String(), query.Args...)
   4.225 +	if err != nil {
   4.226 +		return false, err
   4.227 +	}
   4.228 +	var found bool
   4.229 +	for rows.Next() {
   4.230 +		found = true
   4.231 +	}
   4.232 +	if err = rows.Err(); err != nil {
   4.233 +		return found, err
   4.234 +	}
   4.235 +	return found, nil
   4.236 +}
   4.237 +
   4.238 +func (p *postgres) listEndpointsSQL(client uuid.ID, num, offset int) *pan.Query {
   4.239 +	var endpoint Endpoint
   4.240 +	fields, _ := pan.GetFields(endpoint)
   4.241 +	query := pan.New(pan.POSTGRES, "SELECT "+pan.QueryList(fields)+" FROM "+pan.GetTableName(endpoint))
   4.242 +	query.IncludeWhere()
   4.243 +	query.Include(pan.GetUnquotedColumn(endpoint, "ClientID")+" = ?", client)
   4.244 +	query.IncludeLimit(int64(num))
   4.245 +	query.IncludeOffset(int64(offset))
   4.246 +	return query.FlushExpressions(" ")
   4.247 +}
   4.248 +
   4.249 +func (p *postgres) listEndpoints(client uuid.ID, num, offset int) ([]Endpoint, error) {
   4.250 +	query := p.listEndpointsSQL(client, num, offset)
   4.251 +	rows, err := p.db.Query(query.String(), query.Args...)
   4.252 +	if err != nil {
   4.253 +		return []Endpoint{}, err
   4.254 +	}
   4.255 +	var endpoints []Endpoint
   4.256 +	for rows.Next() {
   4.257 +		var endpoint Endpoint
   4.258 +		err = pan.Unmarshal(rows, &endpoint)
   4.259 +		if err != nil {
   4.260 +			return endpoints, err
   4.261 +		}
   4.262 +		endpoints = append(endpoints, endpoint)
   4.263 +	}
   4.264 +	if err = rows.Err(); err != nil {
   4.265 +		return endpoints, err
   4.266 +	}
   4.267 +	return endpoints, nil
   4.268 +}
   4.269 +
   4.270 +func (p *postgres) countEndpointsSQL(client uuid.ID) *pan.Query {
   4.271 +	var endpoint Endpoint
   4.272 +	query := pan.New(pan.POSTGRES, "SELECT COUNT(*) FROM "+pan.GetTableName(endpoint))
   4.273 +	query.IncludeWhere()
   4.274 +	query.Include(pan.GetUnquotedColumn(endpoint, "ClientID")+" = ?", client)
   4.275 +	return query.FlushExpressions(" ")
   4.276 +}
   4.277 +
   4.278 +func (p *postgres) countEndpoints(client uuid.ID) (int64, error) {
   4.279 +	query := p.countEndpointsSQL(client)
   4.280 +	rows, err := p.db.Query(query.String(), query.Args...)
   4.281 +	if err != nil {
   4.282 +		return 0, err
   4.283 +	}
   4.284 +	var results int64
   4.285 +	for rows.Next() {
   4.286 +		err = pan.Unmarshal(rows, &results)
   4.287 +		if err != nil {
   4.288 +			return results, err
   4.289 +		}
   4.290 +	}
   4.291 +	if err = rows.Err(); err != nil {
   4.292 +		return results, err
   4.293 +	}
   4.294 +	return results, nil
   4.295 +}
     5.1 --- a/client_test.go	Sat Mar 21 18:46:57 2015 -0400
     5.2 +++ b/client_test.go	Sun Mar 22 16:26:37 2015 -0400
     5.3 @@ -25,6 +25,16 @@
     5.4  	clientChangeWebsite
     5.5  )
     5.6  
     5.7 +func init() {
     5.8 +	p, err := NewPostgres("dbname=testdb sslmode=disable")
     5.9 +	if err != nil {
    5.10 +		panic(err)
    5.11 +	}
    5.12 +	if !testing.Short() {
    5.13 +		clientStores = append(clientStores, &p)
    5.14 +	}
    5.15 +}
    5.16 +
    5.17  var clientStores = []clientStore{NewMemstore()}
    5.18  
    5.19  func compareClients(client1, client2 Client) (success bool, field string, val1, val2 interface{}) {
    5.20 @@ -107,14 +117,11 @@
    5.21  		if !success {
    5.22  			t.Fatalf("Expected field %s to be %v, but %T returned %v", field, expectation, store, result)
    5.23  		}
    5.24 -		err = context.DeleteClient(client.ID)
    5.25 +		deleted := true
    5.26 +		err = context.UpdateClient(client.ID, ClientChange{Deleted: &deleted})
    5.27  		if err != nil {
    5.28  			t.Fatalf("Error deleting client from %T: %s", store, err)
    5.29  		}
    5.30 -		err = context.DeleteClient(client.ID)
    5.31 -		if err != ErrClientNotFound {
    5.32 -			t.Fatalf("Expected ErrClientNotFound, got %s from %T", err, store)
    5.33 -		}
    5.34  		retrieved, err = context.GetClient(client.ID)
    5.35  		if err != ErrClientNotFound {
    5.36  			t.Fatalf("Expected ErrClientNotFound from %T, got %+v and %s", store, retrieved, err)
    5.37 @@ -157,7 +164,7 @@
    5.38  		if err != nil {
    5.39  			t.Fatalf("Error saving client to %T: %s", store, err)
    5.40  		}
    5.41 -		err = context.AddEndpoints(client.ID, []Endpoint{endpoint1})
    5.42 +		err = context.AddEndpoints([]Endpoint{endpoint1})
    5.43  		if err != nil {
    5.44  			t.Fatalf("Error adding endpoint to client in %T: %s", store, err)
    5.45  		}
    5.46 @@ -172,7 +179,7 @@
    5.47  		if !success {
    5.48  			t.Fatalf("Expected field %s to be %v, but %T returned %v", field, expectation, store, result)
    5.49  		}
    5.50 -		err = context.AddEndpoints(client.ID, []Endpoint{endpoint2})
    5.51 +		err = context.AddEndpoints([]Endpoint{endpoint2})
    5.52  		if err != nil {
    5.53  			t.Fatalf("Error adding endpoint to client in %T: %s", store, err)
    5.54  		}
    5.55 @@ -237,6 +244,7 @@
    5.56  	for i := 0; i < variations; i++ {
    5.57  		var secret, name, logo, website string
    5.58  		change := ClientChange{}
    5.59 +		client.ID = uuid.NewID()
    5.60  		expectation := client
    5.61  		result := client
    5.62  		if i&clientChangeSecret != 0 {
    5.63 @@ -286,14 +294,11 @@
    5.64  			if !match {
    5.65  				t.Fatalf("Expected field `%s` to be `%v`, got `%v` from %T", field, expected, got, store)
    5.66  			}
    5.67 -			err = context.DeleteClient(client.ID)
    5.68 +			deleted := true
    5.69 +			err = context.UpdateClient(client.ID, ClientChange{Deleted: &deleted})
    5.70  			if err != nil {
    5.71  				t.Fatalf("Error deleting client from %T: %s", store, err)
    5.72  			}
    5.73 -			err = context.UpdateClient(client.ID, change)
    5.74 -			if err != ErrClientNotFound {
    5.75 -				t.Fatalf("Expected ErrClientNotFound, got %v from %T", err, store)
    5.76 -			}
    5.77  		}
    5.78  	}
    5.79  }
    5.80 @@ -333,11 +338,11 @@
    5.81  		if err != nil {
    5.82  			t.Fatalf("Error saving client in %T: %s", store, err)
    5.83  		}
    5.84 -		err = context.AddEndpoints(client.ID, []Endpoint{endpoint1})
    5.85 +		err = context.AddEndpoints([]Endpoint{endpoint1})
    5.86  		if err != nil {
    5.87  			t.Fatalf("Error saving endpoint in %T: %s", store, err)
    5.88  		}
    5.89 -		err = context.AddEndpoints(client.ID, []Endpoint{endpoint2})
    5.90 +		err = context.AddEndpoints([]Endpoint{endpoint2})
    5.91  		if err != nil {
    5.92  			t.Fatalf("Error saving endpoint in %T: %s", store, err)
    5.93  		}
    5.94 @@ -394,11 +399,11 @@
    5.95  		if err != nil {
    5.96  			t.Fatalf("Error saving client in %T: %s", store, err)
    5.97  		}
    5.98 -		err = context.AddEndpoints(client.ID, []Endpoint{endpoint1})
    5.99 +		err = context.AddEndpoints([]Endpoint{endpoint1})
   5.100  		if err != nil {
   5.101  			t.Fatalf("Error saving endpoint in %T: %s", store, err)
   5.102  		}
   5.103 -		err = context.AddEndpoints(client.ID, []Endpoint{endpoint2})
   5.104 +		err = context.AddEndpoints([]Endpoint{endpoint2})
   5.105  		if err != nil {
   5.106  			t.Fatalf("Error saving endpoint in %T: %s", store, err)
   5.107  		}
     6.1 --- a/context.go	Sat Mar 21 18:46:57 2015 -0400
     6.2 +++ b/context.go	Sun Mar 22 16:26:37 2015 -0400
     6.3 @@ -91,15 +91,6 @@
     6.4  	return c.clients.updateClient(id, change)
     6.5  }
     6.6  
     6.7 -// DeleteClient removes the client with the specified ID from the
     6.8 -// clientStore associated with the Context.
     6.9 -func (c Context) DeleteClient(id uuid.ID) error {
    6.10 -	if c.clients == nil {
    6.11 -		return ErrNoClientStore
    6.12 -	}
    6.13 -	return c.clients.deleteClient(id)
    6.14 -}
    6.15 -
    6.16  // ListClientsByOwner returns a slice of up to num Clients, starting at offset (inclusive)
    6.17  // that have the specified OwnerID in the clientStore associated with the Context.
    6.18  func (c Context) ListClientsByOwner(ownerID uuid.ID, num, offset int) ([]Client, error) {
    6.19 @@ -109,9 +100,8 @@
    6.20  	return c.clients.listClientsByOwner(ownerID, num, offset)
    6.21  }
    6.22  
    6.23 -// AddEndpoints stores the specified Endpoints in the clientStore associated with the Context,
    6.24 -// and associates the newly-stored Endpoints with the Client specified by the passed ID.
    6.25 -func (c Context) AddEndpoints(client uuid.ID, endpoints []Endpoint) error {
    6.26 +// AddEndpoints stores the specified Endpoints in the clientStore associated with the Context.
    6.27 +func (c Context) AddEndpoints(endpoints []Endpoint) error {
    6.28  	if c.clients == nil {
    6.29  		return ErrNoClientStore
    6.30  	}
    6.31 @@ -123,7 +113,7 @@
    6.32  		endpoint.NormalizedURI = u
    6.33  		endpoints[pos] = endpoint
    6.34  	}
    6.35 -	return c.clients.addEndpoints(client, endpoints)
    6.36 +	return c.clients.addEndpoints(endpoints)
    6.37  }
    6.38  
    6.39  // GetEndpoint retrieves the Endpoint with the specified ID from the clientStore associated
     7.1 --- a/oauth2_test.go	Sat Mar 21 18:46:57 2015 -0400
     7.2 +++ b/oauth2_test.go	Sun Mar 22 16:26:37 2015 -0400
     7.3 @@ -56,7 +56,7 @@
     7.4  	if err != nil {
     7.5  		t.Fatal("Can't store client:", err)
     7.6  	}
     7.7 -	err = testContext.AddEndpoints(client.ID, []Endpoint{endpoint})
     7.8 +	err = testContext.AddEndpoints([]Endpoint{endpoint})
     7.9  	if err != nil {
    7.10  		t.Fatal("Can't store endpoint:", err)
    7.11  	}
    7.12 @@ -295,7 +295,7 @@
    7.13  		URI:      "https://test.secondbit.org/redirect",
    7.14  		Added:    time.Now().Round(time.Millisecond),
    7.15  	}
    7.16 -	err = testContext.AddEndpoints(client.ID, []Endpoint{endpoint})
    7.17 +	err = testContext.AddEndpoints([]Endpoint{endpoint})
    7.18  	if err != nil {
    7.19  		t.Fatal("Can't store endpoint:", err)
    7.20  	}
    7.21 @@ -315,7 +315,7 @@
    7.22  		URI:      "https://test.secondbit.org/redirect",
    7.23  		Added:    time.Now().Round(time.Millisecond),
    7.24  	}
    7.25 -	err = testContext.AddEndpoints(client.ID, []Endpoint{endpoint2})
    7.26 +	err = testContext.AddEndpoints([]Endpoint{endpoint2})
    7.27  	if err != nil {
    7.28  		t.Fatal("Can't store endpoint:", err)
    7.29  	}
    7.30 @@ -372,7 +372,7 @@
    7.31  	if err != nil {
    7.32  		t.Fatal("Can't store client:", err)
    7.33  	}
    7.34 -	err = testContext.AddEndpoints(client.ID, []Endpoint{endpoint})
    7.35 +	err = testContext.AddEndpoints([]Endpoint{endpoint})
    7.36  	if err != nil {
    7.37  		t.Fatal("Can't store endpoint:", err)
    7.38  	}
    7.39 @@ -478,7 +478,7 @@
    7.40  	if err != nil {
    7.41  		t.Fatal("Can't store client:", err)
    7.42  	}
    7.43 -	err = testContext.AddEndpoints(client.ID, []Endpoint{endpoint})
    7.44 +	err = testContext.AddEndpoints([]Endpoint{endpoint})
    7.45  	if err != nil {
    7.46  		t.Fatal("Can't store endpoint:", err)
    7.47  	}
     8.1 --- a/sql/postgres_init.sql	Sat Mar 21 18:46:57 2015 -0400
     8.2 +++ b/sql/postgres_init.sql	Sun Mar 22 16:26:37 2015 -0400
     8.3 @@ -21,3 +21,22 @@
     8.4  	created TIMESTAMPTZ NOT NULL,
     8.5  	last_used TIMESTAMPTZ NOT NULL
     8.6  );
     8.7 +
     8.8 +CREATE TABLE IF NOT EXISTS clients (
     8.9 +	id VARCHAR(36) PRIMARY KEY,
    8.10 +	secret VARCHAR(64) NOT NULL,
    8.11 +	owner_id VARCHAR(36) NOT NULL,
    8.12 +	name VARCHAR(32) NOT NULL,
    8.13 +	logo VARCHAR(512) NOT NULL,
    8.14 +	website VARCHAR(140) NOT NULL,
    8.15 +	type VARCHAR(16) NOT NULL,
    8.16 +	deleted BOOLEAN NOT NULL
    8.17 +);
    8.18 +
    8.19 +CREATE TABLE IF NOT EXISTS endpoints (
    8.20 +	id VARCHAR(36) PRIMARY KEY,
    8.21 +	client_id VARCHAR(36) NOT NULL,
    8.22 +	uri VARCHAR(512) NOT NULL,
    8.23 +	normalized_uri VARCHAR(512) NOT NULL,
    8.24 +	added TIMESTAMPTZ NOT NULL
    8.25 +);