File size: 1,380 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package mockslack

import (
	"context"
	"net/http"
)

// OAuthAccessOpts contains parameters for an OAuthAccess API call.
type OAuthAccessOpts struct {
	ClientID     string
	ClientSecret string
	Code         string
}

// OAuthAccess will exchange a temporary code for an access token.
func (st *API) OAuthAccess(ctx context.Context, opts OAuthAccessOpts) (*AuthToken, error) {
	st.mx.Lock()
	defer st.mx.Unlock()

	app := st.apps[opts.ClientID]
	if app == nil {
		return nil, &response{Err: "invalid_client_id"}
	}

	if app.Secret != opts.ClientSecret {
		return nil, &response{Err: "bad_client_secret"}
	}

	tok := st.tokenCodes[opts.Code]
	if tok == nil || tok.ClientID != opts.ClientID {
		return nil, &response{Err: "invalid_code"}
	}

	delete(st.tokenCodes, opts.Code)

	return tok.AuthToken, nil
}

// ServeOAuthAccess serves a request to the `oauth.access` API call.
//
// https://api.slack.com/methods/oauth.access
func (s *Server) ServeOAuthAccess(w http.ResponseWriter, req *http.Request) {
	usr, pass, _ := req.BasicAuth()
	tok, err := s.API().OAuthAccess(req.Context(), OAuthAccessOpts{ClientID: usr, ClientSecret: pass, Code: req.FormValue("code")})
	if respondErr(w, err) {
		return
	}

	var resp struct {
		AccessToken string `json:"access_token"`
		UserID      string `json:"user_id"`
	}
	resp.AccessToken = tok.ID
	resp.UserID = tok.User

	respondWith(w, resp)
}