Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using a bot account. #83

Merged
merged 4 commits into from
Jun 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,8 @@ __If you are using GitHub Enterprise, replace all GitHub links below with your G

### Step 3: Configure plugin in Mattermost

1. Create a new Mattermost user, through the regular UI or the CLI with the username `github`.
1. Make sure you do not have an existing user account with the name `github`. You probably do if you are upgrading from a previous version of the plugin. If you do, convert it to a bot account by using the Mattermost CLI command `mattermost user convert --bot github`. If you where using an account that was not named github for the github plugin, rename it go github then convert it to a bot account.
2. Go to **System Console > Plugins > GitHub** and do the following values:
- Set "github" as the **User**.
- Generate a new value for **At Rest Encryption Key**.
- (Optional) Lock the plugin to a single GitHub organization by setting the **GitHub Organization** field to the name of your GitHub organization.
- (Optional) Allow the plugin to receive notifications from private repositories by setting **Enable Private Repositories** to true.
Expand Down Expand Up @@ -89,7 +88,6 @@ If you are running Mattermost v5.11 or earlier in [High Availability mode](https
"githuboauthclientid": "<your oauth client id, from step 2 above>",
"githuboauthclientsecret": "<your oauth client secret, from step 2 above>",
"githuborg": "<your github org>",
"username": "<your user account to attach the plugin to, from step 4 above>",
"webhooksecret": "<your webhook secret, from step 3 above>"
},
...
Expand Down
7 changes: 1 addition & 6 deletions plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"name": "GitHub",
"description": "GitHub plugin for Mattermost.",
"version": "0.9.1",
"min_server_version": "5.12.0",
"server": {
"executables": {
"linux-amd64": "server/dist/plugin-linux-amd64",
Expand Down Expand Up @@ -34,12 +35,6 @@
"type": "generated",
"help_text": "The webhook secret set in GitHub."
},
{
"key": "Username",
"display_name": "User",
"type": "username",
"help_text": "Select the username of the user that the plugin will post with. This can be any user, the name and icon will be overridden when posting."
},
{
"key": "EncryptionKey",
"display_name": "At Rest Encryption Key",
Expand Down
21 changes: 0 additions & 21 deletions server/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
Expand All @@ -22,7 +19,6 @@ import (

const (
API_ERROR_ID_NOT_CONNECTED = "not_connected"
GITHUB_USERNAME = "GitHub Plugin"
)

type APIErrorResponse struct {
Expand Down Expand Up @@ -50,8 +46,6 @@ func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Req
switch path := r.URL.Path; path {
case "/webhook":
p.handleWebhook(w, r)
case "/assets/profile.png":
p.handleProfileImage(w, r)
case "/oauth/connect":
p.connectUserToGitHub(w, r)
case "/oauth/complete":
Expand Down Expand Up @@ -211,21 +205,6 @@ func (p *Plugin) completeConnectUserToGitHub(w http.ResponseWriter, r *http.Requ
w.Write([]byte(html))
}

func (p *Plugin) handleProfileImage(w http.ResponseWriter, r *http.Request) {
hanzei marked this conversation as resolved.
Show resolved Hide resolved
config := p.getConfiguration()

img, err := os.Open(filepath.Join(config.PluginsDirectory, manifest.Id, "assets", "profile.png"))
if err != nil {
http.NotFound(w, r)
mlog.Error("Unable to read github profile image, err=" + err.Error())
return
}
defer img.Close()

w.Header().Set("Content-Type", "image/png")
io.Copy(w, img)
}

type ConnectedResponse struct {
Connected bool `json:"connected"`
GitHubUsername string `json:"github_username"`
Expand Down
86 changes: 54 additions & 32 deletions server/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,13 @@ func getCommand() *model.Command {
}
}

func (p *Plugin) getCommandResponse(responseType, text string) *model.CommandResponse {
return &model.CommandResponse{
ResponseType: responseType,
Text: text,
Username: GITHUB_USERNAME,
IconURL: p.getConfiguration().ProfileImageURL,
Type: model.POST_DEFAULT,
func (p *Plugin) postCommandResponse(args *model.CommandArgs, text string) {
crspeller marked this conversation as resolved.
Show resolved Hide resolved
post := &model.Post{
UserId: p.BotUserID,
ChannelId: args.ChannelId,
Message: text,
}
_ = p.API.SendEphemeralPost(args.UserId, post)
}

func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
crspeller marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -73,11 +72,12 @@ func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*mo
if action == "connect" {
config := p.API.GetConfig()
if config.ServiceSettings.SiteURL == nil {
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, "Encountered an error connecting to GitHub."), nil
p.postCommandResponse(args, "Encountered an error connecting to GitHub.")
return &model.CommandResponse{}, nil
}

resp := p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, fmt.Sprintf("[Click here to link your GitHub account.](%s/plugins/github/oauth/connect)", *config.ServiceSettings.SiteURL))
return resp, nil
p.postCommandResponse(args, fmt.Sprintf("[Click here to link your GitHub account.](%s/plugins/github/oauth/connect)", *config.ServiceSettings.SiteURL))
return &model.CommandResponse{}, nil
}

ctx := context.Background()
Expand All @@ -89,7 +89,8 @@ func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*mo
if apiErr.ID == API_ERROR_ID_NOT_CONNECTED {
text = "You must connect your account to GitHub first. Either click on the GitHub logo in the bottom left of the screen or enter `/github connect`."
}
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, text), nil
p.postCommandResponse(args, text)
return &model.CommandResponse{}, nil
}

githubClient = p.githubConnect(*info.Token)
Expand All @@ -101,11 +102,13 @@ func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*mo

txt := ""
if len(parameters) == 0 {
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, "Please specify a repository or 'list' command."), nil
p.postCommandResponse(args, "Please specify a repository or 'list' command.")
return &model.CommandResponse{}, nil
} else if len(parameters) == 1 && parameters[0] == "list" {
subs, err := p.GetSubscriptionsByChannel(args.ChannelId)
if err != nil {
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, err.Error()), nil
p.postCommandResponse(args, err.Error())
return &model.CommandResponse{}, nil
}

if len(subs) == 0 {
Expand All @@ -116,78 +119,96 @@ func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*mo
for _, sub := range subs {
txt += fmt.Sprintf("* `%s` - %s\n", strings.Trim(sub.Repository, "/"), sub.Features)
}
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, txt), nil
p.postCommandResponse(args, txt)
return &model.CommandResponse{}, nil
} else if len(parameters) > 1 {
features = strings.Join(parameters[1:], " ")
}

_, owner, repo := parseOwnerAndRepo(parameters[0], config.EnterpriseBaseURL)
if repo == "" {
if err := p.SubscribeOrg(context.Background(), githubClient, args.UserId, owner, args.ChannelId, features); err != nil {
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, err.Error()), nil
p.postCommandResponse(args, err.Error())
return &model.CommandResponse{}, nil
}

return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, fmt.Sprintf("Successfully subscribed to organization %s.", owner)), nil
p.postCommandResponse(args, fmt.Sprintf("Successfully subscribed to organization %s.", owner))
return &model.CommandResponse{}, nil
}

if err := p.Subscribe(context.Background(), githubClient, args.UserId, owner, repo, args.ChannelId, features); err != nil {
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, err.Error()), nil
p.postCommandResponse(args, err.Error())
return &model.CommandResponse{}, nil
}

return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, fmt.Sprintf("Successfully subscribed to %s.", repo)), nil
p.postCommandResponse(args, fmt.Sprintf("Successfully subscribed to %s.", repo))
return &model.CommandResponse{}, nil
case "unsubscribe":
if len(parameters) == 0 {
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, "Please specify a repository."), nil
p.postCommandResponse(args, "Please specify a repository.")
return &model.CommandResponse{}, nil
}

repo := parameters[0]

if err := p.Unsubscribe(args.ChannelId, repo); err != nil {
mlog.Error(err.Error())
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, "Encountered an error trying to unsubscribe. Please try again."), nil
p.postCommandResponse(args, "Encountered an error trying to unsubscribe. Please try again.")
return &model.CommandResponse{}, nil
}

return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, fmt.Sprintf("Succesfully unsubscribed from %s.", repo)), nil
p.postCommandResponse(args, fmt.Sprintf("Succesfully unsubscribed from %s.", repo))
return &model.CommandResponse{}, nil
case "disconnect":
p.disconnectGitHubAccount(args.UserId)
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, "Disconnected your GitHub account."), nil
p.postCommandResponse(args, "Disconnected your GitHub account.")
return &model.CommandResponse{}, nil
case "todo":
text, err := p.GetToDo(ctx, info.GitHubUsername, githubClient)
if err != nil {
mlog.Error(err.Error())
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, "Encountered an error getting your to do items."), nil
p.postCommandResponse(args, "Encountered an error getting your to do items.")
return &model.CommandResponse{}, nil
}
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, text), nil
p.postCommandResponse(args, text)
return &model.CommandResponse{}, nil
case "me":
gitUser, _, err := githubClient.Users.Get(ctx, "")
if err != nil {
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, "Encountered an error getting your GitHub profile."), nil
p.postCommandResponse(args, "Encountered an error getting your GitHub profile.")
return &model.CommandResponse{}, nil
}

text := fmt.Sprintf("You are connected to GitHub as:\n# [![image](%s =40x40)](%s) [%s](%s)", gitUser.GetAvatarURL(), gitUser.GetHTMLURL(), gitUser.GetLogin(), gitUser.GetHTMLURL())
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, text), nil
p.postCommandResponse(args, text)
return &model.CommandResponse{}, nil
case "help":
text := "###### Mattermost GitHub Plugin - Slash Command Help\n" + strings.Replace(COMMAND_HELP, "|", "`", -1)
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, text), nil
p.postCommandResponse(args, text)
return &model.CommandResponse{}, nil
case "":
text := "###### Mattermost GitHub Plugin - Slash Command Help\n" + strings.Replace(COMMAND_HELP, "|", "`", -1)
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, text), nil
p.postCommandResponse(args, text)
return &model.CommandResponse{}, nil
case "settings":
if len(parameters) < 2 {
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, "Please specify both a setting and value. Use `/github help` for more usage information."), nil
p.postCommandResponse(args, "Please specify both a setting and value. Use `/github help` for more usage information.")
return &model.CommandResponse{}, nil
}

setting := parameters[0]
if setting != SETTING_NOTIFICATIONS && setting != SETTING_REMINDERS {
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, "Unknown setting."), nil
p.postCommandResponse(args, "Unknown setting.")
return &model.CommandResponse{}, nil
}

strValue := parameters[1]
value := false
if strValue == SETTING_ON {
value = true
} else if strValue != SETTING_OFF {
return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, "Invalid value. Accepted values are: \"on\" or \"off\"."), nil
p.postCommandResponse(args, "Invalid value. Accepted values are: \"on\" or \"off\".")
return &model.CommandResponse{}, nil
}

if setting == SETTING_NOTIFICATIONS {
Expand All @@ -204,7 +225,8 @@ func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*mo

p.storeGitHubUserInfo(info)

return p.getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, "Settings updated."), nil
p.postCommandResponse(args, "Settings updated.")
return &model.CommandResponse{}, nil
}

return &model.CommandResponse{}, nil
Expand Down
13 changes: 1 addition & 12 deletions server/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
// copy appropriate for your types.
type configuration struct {
GitHubOrg string
Username string
GitHubOAuthClientID string
GitHubOAuthClientSecret string
WebhookSecret string
Expand All @@ -30,7 +29,6 @@ type configuration struct {
EnterpriseBaseURL string
EnterpriseUploadURL string
PluginsDirectory string
ProfileImageURL string
}

// Clone shallow copies the configuration. Your implementation may require a deep copy if
Expand All @@ -54,10 +52,6 @@ func (c *configuration) IsValid() error {
return fmt.Errorf("Must have an encryption key")
}

if c.Username == "" {
return fmt.Errorf("Need a user to make posts as")
}

return nil
}

Expand Down Expand Up @@ -99,15 +93,10 @@ func (p *Plugin) setConfiguration(configuration *configuration, serverConfigurat
panic("setConfiguration called with the existing configuration")
}

// PluginDirectory & ProfileImageURL should be set based on server configuration and not the plugin configuration
// PluginDirectory should be set based on server configuration and not the plugin configuration
if serverConfiguration.PluginSettings.Directory != nil {
configuration.PluginsDirectory = *serverConfiguration.PluginSettings.Directory
}
if serverConfiguration.ServiceSettings.SiteURL != nil {
// Temporary patch until issue with image proxy is solved
configuration.ProfileImageURL = "https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png"
//configuration.ProfileImageURL = path.Join(*serverConfiguration.ServiceSettings.SiteURL, "plugins", manifest.Id, "assets", "profile.png")
}

p.configuration = configuration
}
Expand Down
Loading