Skip to content

Commit

Permalink
Merge pull request #1803 from target/application-name-config
Browse files Browse the repository at this point in the history
config/general: add application name field
  • Loading branch information
KatieMSB authored Aug 30, 2021
2 parents a5ea762 + 6c98439 commit e742d6d
Show file tree
Hide file tree
Showing 15 changed files with 73 additions and 44 deletions.
2 changes: 1 addition & 1 deletion app/inithttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ func (app *App) initHTTP(ctx context.Context) error {
})

mux.Handle("/api/graphql", app.graphql2.Handler())
mux.Handle("/api/graphql/explore", app.graphql2.PlayHandler())
mux.HandleFunc("/api/graphql/explore", app.graphql2.PlayHandler)

mux.HandleFunc("/api/v2/config", app.ConfigStore.ServeConfig)

Expand Down
13 changes: 13 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type Config struct {
fallbackURL string

General struct {
ApplicationName string `public:"true" info:"The name used in messaging and page titles. Defaults to \"GoAlert\"."`
PublicURL string `public:"true" info:"Publicly routable URL for UI links and API calls."`
GoogleAnalyticsID string `public:"true"`
NotificationDisclaimer string `public:"true" info:"Disclaimer text for receiving pre-recorded notifications (appears on profile page)."`
Expand Down Expand Up @@ -307,6 +308,14 @@ func (cfg Config) ValidReferer(reqURL, ref string) bool {
return false
}

// ApplicationName will return the General.ApplicationName
func (cfg Config) ApplicationName() string {
if cfg.General.ApplicationName == "" {
return "GoAlert"
}
return cfg.General.ApplicationName
}

// PublicURL will return the General.PublicURL or a fallback address (i.e. the app listening port).
func (cfg Config) PublicURL() string {
if cfg.General.PublicURL == "" {
Expand Down Expand Up @@ -346,6 +355,10 @@ func (cfg Config) Validate() error {
)
}

if cfg.General.ApplicationName != "" {
err = validate.Many(err, validate.ASCII("General.ApplicationName", cfg.General.ApplicationName, 0, 32))
}

validateKey := func(fname, val string) error { return validate.ASCII(fname, val, 0, 128) }
validatePath := func(fname, val string) error {
if val == "" {
Expand Down
1 change: 1 addition & 0 deletions config/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@ func (s *Store) updateConfigTx(ctx context.Context, tx *sql.Tx, fn func(Config)
func (s *Store) Config() Config {
s.mx.RLock()
cfg := s.rawCfg

s.mx.RUnlock()
return cfg
}
39 changes: 19 additions & 20 deletions graphql2/graphqlapp/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,31 +85,30 @@ type App struct {
FormatDestFunc func(context.Context, notification.DestType, string) string
}

func mustAuth(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
err := permission.LimitCheckAny(req.Context())
if errutil.HTTPError(req.Context(), w, err) {
return
}
func (a *App) PlayHandler(w http.ResponseWriter, req *http.Request) {
var data struct {
ApplicationName string
Version string
PackageName string
}

h.ServeHTTP(w, req)
})
}
ctx := req.Context()

func (a *App) PlayHandler() http.Handler {
var data struct {
Version string
PackageName string
err := permission.LimitCheckAny(ctx)
if errutil.HTTPError(ctx, w, err) {
return
}

cfg := config.FromContext(ctx)

data.ApplicationName = cfg.ApplicationName()
data.Version = playVersion
data.PackageName = playPackageName
return mustAuth(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
err := playTmpl.Execute(w, data)
if err != nil {
log.Log(req.Context(), err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}))

err = playTmpl.Execute(w, data)
if errutil.HTTPError(ctx, w, err) {
return
}
}

type fieldErr struct {
Expand Down
2 changes: 1 addition & 1 deletion graphql2/graphqlapp/playground.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
href="//cdn.jsdelivr.net/npm/{{ .PackageName }}@{{ .Version }}/build/favicon.png"
/>
<script src="//cdn.jsdelivr.net/npm/{{ .PackageName }}@{{ .Version }}/build/static/js/middleware.js"></script>
<title>GoAlert - GraphQL API</title>
<title>{{ .ApplicationName }} - GraphQL API</title>
<style type="text/css">
html {
font-family: 'Open Sans', sans-serif;
Expand Down
8 changes: 2 additions & 6 deletions graphql2/graphqlapp/slack.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package graphqlapp

import (
"bytes"
context "context"
"context"
_ "embed"
"html/template"
"sort"
Expand Down Expand Up @@ -103,11 +103,7 @@ func (q *Query) SlackChannels(ctx context.Context, input *graphql2.SlackChannelS
//go:embed slack.manifest.yaml
var manifestYAML string

var tmpl = template.Must(template.New("slack.manifest.yaml").Funcs(template.FuncMap{
"appName": func() string {
return "GoAlert" // todo: use Application Name cfg value
},
}).Parse(manifestYAML))
var tmpl = template.Must(template.New("slack.manifest.yaml").Parse(manifestYAML))

func (q *Query) GenerateSlackAppManifest(ctx context.Context) (string, error) {
err := permission.LimitCheckAny(ctx, permission.Admin)
Expand Down
4 changes: 2 additions & 2 deletions graphql2/graphqlapp/slack.manifest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ _metadata:
major_version: 1
minor_version: 1
display_information:
name: '{{appName}}'
name: '{{.ApplicationName}}'
settings:
interactivity:
is_enabled: true
request_url: '{{.CallbackURL "/api/v2/slack/message-action"}}'
message_menu_options_url: '{{.CallbackURL "/api/v2/slack/menu-options"}}'
features:
bot_user:
display_name: '{{appName}}'
display_name: '{{.ApplicationName}}'
always_online: true
oauth_config:
scopes:
Expand Down
4 changes: 4 additions & 0 deletions graphql2/mapconfig.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 17 additions & 12 deletions web/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"embed"
"encoding/hex"
"fmt"
"github.com/target/goalert/config"
"github.com/target/goalert/util/errutil"
"io/fs"
"net/http"
"net/http/httputil"
Expand Down Expand Up @@ -67,19 +69,22 @@ func NewHandler(urlStr, prefix string) (http.Handler, error) {
extraScripts = []string{"vendor.js"}
}

var buf bytes.Buffer
err := indexTmpl.Execute(&buf, renderData{
Prefix: prefix,
ExtraScripts: extraScripts,
})
if err != nil {
return nil, err
}
h := sha256.New()
h.Write(buf.Bytes())
indexETag := fmt.Sprintf(`"sha256-%s"`, hex.EncodeToString(h.Sum(nil)))

mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
cfg := config.FromContext(req.Context())

var buf bytes.Buffer
err := indexTmpl.Execute(&buf, renderData{
ApplicationName: cfg.ApplicationName(),
Prefix: prefix,
ExtraScripts: extraScripts,
})
if errutil.HTTPError(req.Context(), w, err) {
return
}
h := sha256.New()
h.Write(buf.Bytes())
indexETag := fmt.Sprintf(`"sha256-%s"`, hex.EncodeToString(h.Sum(nil)))

w.Header().Set("Cache-Control", "private; max-age=60, stale-while-revalidate=600, stale-if-error=259200")
w.Header().Set("ETag", indexETag)
http.ServeContent(w, req, "/", time.Time{}, bytes.NewReader(buf.Bytes()))
Expand Down
3 changes: 3 additions & 0 deletions web/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ func AppVersion() string {
}

type renderData struct {
// Name set in config used for the application.
ApplicationName string

// Prefix is the URL prefix for the GoAlert application.
Prefix string

Expand Down
3 changes: 2 additions & 1 deletion web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<meta http-equiv="x-goalert-git-commit" content="{{.GitCommit}}" />
<meta http-equiv="x-goalert-git-tree-state" content="{{.GitTreeState}}" />

<title>GoAlert</title>
<title>{{.ApplicationName}}</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="preconnect" href="https://gravatar.com" />
<link
Expand Down Expand Up @@ -40,6 +40,7 @@
<div id="graceful-unmount"></div>
<script>
pathPrefix = {{.PathPrefix}};
applicationName = {{.ApplicationName}};
</script>
{{- $prefix := .Prefix}} {{- range .ExtraScripts}}
<script src="{{$prefix}}/static/{{.}}"></script>
Expand Down
2 changes: 2 additions & 0 deletions web/src/app/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ declare global {
namespace NodeJS {
interface Global {
pathPrefix: string
applicationName: string
GOALERT_VERSION: string
Cypress?: any
}
Expand All @@ -15,6 +16,7 @@ declare let __webpack_public_path__: string
declare let __webpack_require__: any

export const pathPrefix = global.pathPrefix
export const applicationName = global.applicationName

if (typeof __webpack_require__ !== 'undefined')
// eslint-disable-next-line
Expand Down
5 changes: 4 additions & 1 deletion web/src/app/main/components/ToolbarTitle.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { gql, useQuery } from '@apollo/client'
import { startCase } from 'lodash'
import AppLink from '../../util/AppLink'
import useWidth from '../../util/useWidth'
import { useConfigValue } from '../../util/RequireConfig'
import { applicationName as appName } from '../../env'

const useStyles = makeStyles(() => ({
backPage: {
Expand Down Expand Up @@ -94,9 +96,10 @@ NameLoader.propTypes = {
function ToolbarTitle() {
const width = useWidth()
const classes = useStyles()
const [applicationName] = useConfigValue('General.ApplicationName')

const renderTitle = (title) => {
document.title = `GoAlert - ${title}`
document.title = `${applicationName || appName} - ${title}`

return (
<Typography
Expand Down
1 change: 1 addition & 0 deletions web/src/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ declare namespace NodeJS {
export interface Global {
__webpack_public_path__: string
pathPrefix: string
applicationName: string
GOALERT_VERSION: string
}

Expand Down
1 change: 1 addition & 0 deletions web/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,7 @@ export interface Notice {
export type NoticeType = 'WARNING' | 'ERROR' | 'INFO'

type ConfigID =
| 'General.ApplicationName'
| 'General.PublicURL'
| 'General.GoogleAnalyticsID'
| 'General.NotificationDisclaimer'
Expand Down

0 comments on commit e742d6d

Please sign in to comment.