2
0

slack.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package slack
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "github.com/porter-dev/porter/internal/models/integrations"
  7. "golang.org/x/oauth2"
  8. )
  9. func TokenToSlackIntegration(token *oauth2.Token) (*integrations.SlackIntegration, error) {
  10. // cast the "incoming_webhook" field to a map[string]string
  11. webhookConfig, ok := token.Extra("incoming_webhook").(map[string]interface{})
  12. if !ok {
  13. return nil, fmt.Errorf("could not get incoming webhook field from token")
  14. }
  15. teamInfo, err := getTeamInfo(token)
  16. if err != nil {
  17. return nil, err
  18. }
  19. return &integrations.SlackIntegration{
  20. SharedOAuthModel: integrations.SharedOAuthModel{
  21. AccessToken: []byte(token.AccessToken),
  22. },
  23. TeamID: teamInfo.Team.ID,
  24. TeamName: teamInfo.Team.Name,
  25. TeamIconURL: teamInfo.Team.Icon.Image132,
  26. Channel: webhookConfig["channel"].(string),
  27. ChannelID: webhookConfig["channel_id"].(string),
  28. ConfigurationURL: webhookConfig["configuration_url"].(string),
  29. Webhook: []byte(webhookConfig["url"].(string)),
  30. }, nil
  31. }
  32. type teamInfoResponse struct {
  33. OK bool `json:"ok"`
  34. Team struct {
  35. ID string `json:"id"`
  36. Name string `json:"name"`
  37. Icon struct {
  38. Image132 string `json:"image_132"`
  39. }
  40. } `json:"team"`
  41. }
  42. func getTeamInfo(token *oauth2.Token) (*teamInfoResponse, error) {
  43. url := "https://slack.com/api/team.info"
  44. // Create a new request using http
  45. req, err := http.NewRequest("GET", url, nil)
  46. // add authorization header to the request
  47. req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token.AccessToken))
  48. // Send req using http Client
  49. client := &http.Client{}
  50. resp, err := client.Do(req)
  51. if err != nil {
  52. return nil, err
  53. }
  54. defer resp.Body.Close()
  55. teamInfo := teamInfoResponse{}
  56. err = json.NewDecoder(resp.Body).Decode(&teamInfo)
  57. if err != nil {
  58. return nil, err
  59. }
  60. return &teamInfo, nil
  61. }