Support email verification.
The bulk of this commit is auto-modifying files to export variables (mostly our
request error types and our response type) so that they can be reused in a Go
client for that API.
We also implement the beginnings of a Go client for that API, implementing the
bare minimum we need for our immediate purposes: the ability to retrieve
information about a Login.
This, of course, means we need an API endpoint that will return information
about a Login, which in turn required us to implement a GetLogin method in our
profileStore. Which got in-memory and postgres implementations.
That done, we could add the Verification field and Verified field to the Login
type, to keep track of whether we've verified the user's ownership of those
communication methods (if the Login is, in fact, a communication method). This
required us to update sql/postgres_init.sql to account for the new fields we're
tracking. It also means that when creating a Login, we had to generate a UUID to
use as the Verification field.
To make things complete, we needed a verifyLogin method on the profileStore to
mark a Login as verified. That, in turn, required an endpoint to control this
through the API. While doing so, I lumped things together in an UpdateLogin
handler just so we could reuse the endpoint and logic when resending a
verification email that may have never reached the user, for whatever reason
(the quintessential "send again" button).
Finally, we implemented an email_verification listener that will pull
email_verification events off NSQ, check for the requisite data integrity, and
use mailgun to email out a verification/welcome email.
11 "code.secondbit.org/uuid.hg"
13 "github.com/dgrijalva/jwt-go"
17 defaultTokenExpiration = 900 // fifteen minutes
21 RegisterGrantType("refresh_token", GrantType{
22 Validate: refreshTokenValidate,
23 Invalidate: refreshTokenInvalidate,
25 ReturnToken: RenderJSONToken,
26 AuditString: refreshTokenAuditString,
31 // ErrNoTokenStore is returned when a Context tries to act on a tokenStore without setting one first.
32 ErrNoTokenStore = errors.New("no tokenStore was specified for the Context")
33 // ErrTokenNotFound is returned when a Token is requested but not found in a tokenStore.
34 ErrTokenNotFound = errors.New("token not found in tokenStore")
35 // ErrTokenAlreadyExists is returned when a Token is added to a tokenStore, but another Token with
36 // the same AccessToken property already exists in the tokenStore.
37 ErrTokenAlreadyExists = errors.New("token already exists in tokenStore")
40 // Token represents an access and/or refresh token that the Client can use to access user data
41 // or obtain a new access token.
55 func (t Token) GenerateAccessToken(privateKey []byte) (string, error) {
56 access := jwt.New(jwt.SigningMethodHS256)
57 access.Claims["iss"] = t.ClientID
58 access.Claims["sub"] = t.ProfileID
59 access.Claims["exp"] = t.Created.Add(defaultTokenExpiration * time.Second).Unix()
60 access.Claims["nbf"] = t.Created.Add(-2 * time.Minute).Unix()
61 access.Claims["iat"] = t.Created.Unix()
62 access.Claims["scope"] = strings.Join(t.Scopes.Strings(), " ")
63 return access.SignedString(privateKey)
66 // BUG(paddy): Now that access tokens are generated and have a meaning, refresh tokens should be the primary key
68 type tokenStore interface {
69 getToken(token string, refresh bool) (Token, error)
70 saveToken(token Token) error
71 revokeToken(token string) error
72 getTokensByProfileID(profileID uuid.ID, num, offset int) ([]Token, error)
73 revokeTokensByProfileID(profileID uuid.ID) error
74 revokeTokensByClientID(clientID uuid.ID) error
77 func (m *memstore) getToken(token string, refresh bool) (Token, error) {
79 t, err := m.lookupTokenByRefresh(token)
86 defer m.tokenLock.RUnlock()
87 result, ok := m.tokens[token]
89 return Token{}, ErrTokenNotFound
94 func (m *memstore) saveToken(token Token) error {
96 defer m.tokenLock.Unlock()
97 _, ok := m.tokens[token.AccessToken]
99 return ErrTokenAlreadyExists
101 m.tokens[token.AccessToken] = token
102 if token.RefreshToken != "" {
103 m.refreshTokenLookup[token.RefreshToken] = token.AccessToken
105 if _, ok = m.profileTokenLookup[token.ProfileID.String()]; ok {
106 m.profileTokenLookup[token.ProfileID.String()] = append(m.profileTokenLookup[token.ProfileID.String()], token.AccessToken)
108 m.profileTokenLookup[token.ProfileID.String()] = []string{token.AccessToken}
113 func (m *memstore) revokeToken(token string) error {
114 token, err := m.lookupTokenByRefresh(token)
119 defer m.tokenLock.Unlock()
120 t, ok := m.tokens[token]
122 return ErrTokenNotFound
129 func (m *memstore) revokeTokensByProfileID(profileID uuid.ID) error {
130 ids, err := m.lookupTokensByProfileID(profileID.String())
135 return ErrProfileNotFound
138 defer m.tokenLock.Unlock()
139 for _, id := range ids {
140 token := m.tokens[id]
147 func (m *memstore) revokeTokensByClientID(clientID uuid.ID) error {
149 defer m.tokenLock.Unlock()
150 for id, token := range m.tokens {
151 if !token.ClientID.Equal(clientID) {
160 func (m *memstore) getTokensByProfileID(profileID uuid.ID, num, offset int) ([]Token, error) {
161 ids, err := m.lookupTokensByProfileID(profileID.String())
163 return []Token{}, err
165 if len(ids) > num+offset {
166 ids = ids[offset : num+offset]
167 } else if len(ids) > offset {
170 return []Token{}, nil
173 for _, id := range ids {
174 token, err := m.getToken(id, false)
176 return []Token{}, err
178 tokens = append(tokens, token)
183 func refreshTokenValidate(w http.ResponseWriter, r *http.Request, context Context) (scopes Scopes, profileID uuid.ID, valid bool) {
184 enc := json.NewEncoder(w)
185 refresh := r.PostFormValue("refresh_token")
187 w.WriteHeader(http.StatusBadRequest)
188 renderJSONError(enc, "invalid_request")
191 token, err := context.GetToken(refresh, true)
193 if err == ErrTokenNotFound {
194 w.WriteHeader(http.StatusBadRequest)
195 renderJSONError(enc, "invalid_grant")
198 log.Println("Error exchanging refresh token:", err)
199 w.WriteHeader(http.StatusInternalServerError)
200 renderJSONError(enc, "server_error")
203 clientID, _, ok := getClientAuth(w, r, true)
207 if !token.ClientID.Equal(clientID) {
208 w.WriteHeader(http.StatusBadRequest)
209 renderJSONError(enc, "invalid_grant")
213 w.WriteHeader(http.StatusBadRequest)
214 renderJSONError(enc, "invalid_grant")
217 return token.Scopes, token.ProfileID, true
220 func refreshTokenInvalidate(r *http.Request, context Context) error {
221 refresh := r.PostFormValue("refresh_token")
223 return ErrTokenNotFound
225 return context.RevokeToken(refresh)
228 func refreshTokenAuditString(r *http.Request) string {
229 return "refresh_token:" + r.PostFormValue("refresh_token")