feat: display api key on user interface (resolve #24)

This commit is contained in:
Ferdinand Mütsch 2020-05-24 21:19:05 +02:00
parent b92a064eb1
commit 2cca2cb0bb
8 changed files with 90 additions and 45 deletions

14
main.go
View File

@ -87,12 +87,12 @@ func main() {
heartbeatHandler := routes.NewHeartbeatHandler(heartbeatService)
summaryHandler := routes.NewSummaryHandler(summaryService)
healthHandler := routes.NewHealthHandler(db)
indexHandler := routes.NewIndexHandler(userService)
publicHandler := routes.NewIndexHandler(userService)
// Setup Routers
router := mux.NewRouter()
indexRouter := router.PathPrefix("/").Subrouter()
summaryRouter := indexRouter.PathPrefix("/summary").Subrouter()
publicRouter := router.PathPrefix("/").Subrouter()
summaryRouter := publicRouter.PathPrefix("/summary").Subrouter()
apiRouter := router.PathPrefix("/api").Subrouter()
// Middlewares
@ -110,10 +110,10 @@ func main() {
apiRouter.Use(corsMiddleware, authenticateMiddleware)
// Public Routes
indexRouter.Path("/").Methods(http.MethodGet).HandlerFunc(indexHandler.Index)
indexRouter.Path("/login").Methods(http.MethodPost).HandlerFunc(indexHandler.Login)
indexRouter.Path("/logout").Methods(http.MethodPost).HandlerFunc(indexHandler.Logout)
indexRouter.Path("/signup").Methods(http.MethodGet, http.MethodPost).HandlerFunc(indexHandler.Signup)
publicRouter.Path("/").Methods(http.MethodGet).HandlerFunc(publicHandler.Index)
publicRouter.Path("/login").Methods(http.MethodPost).HandlerFunc(publicHandler.Login)
publicRouter.Path("/logout").Methods(http.MethodPost).HandlerFunc(publicHandler.Logout)
publicRouter.Path("/signup").Methods(http.MethodGet, http.MethodPost).HandlerFunc(publicHandler.Signup)
// Summary Routes
summaryRouter.Methods(http.MethodGet).HandlerFunc(summaryHandler.Index)

View File

@ -41,4 +41,5 @@ type SummaryViewModel struct {
LanguageColors map[string]string
Error string
Success string
ApiKey string
}

View File

@ -182,33 +182,3 @@ func (h *IndexHandler) handlePostSignup(w http.ResponseWriter, r *http.Request)
msg := url.QueryEscape("account created successfully")
http.Redirect(w, r, fmt.Sprintf("%s/?success=%s", h.config.BasePath, msg), http.StatusFound)
}
func respondAlert(w http.ResponseWriter, error, success, tplName string, status int) {
w.WriteHeader(status)
if tplName == "" {
tplName = "index.tpl.html"
}
templates[tplName].Execute(w, struct {
Error string
Success string
}{Error: error})
}
// TODO: do better
func handleAlerts(w http.ResponseWriter, r *http.Request, tplName string) bool {
if err := r.URL.Query().Get("error"); err != "" {
if err == "unauthorized" {
respondAlert(w, err, "", tplName, http.StatusUnauthorized)
} else {
respondAlert(w, err, "", tplName, http.StatusInternalServerError)
}
return true
}
if success := r.URL.Query().Get("success"); success != "" {
respondAlert(w, "", success, tplName, http.StatusOK)
return true
}
return false
}

View File

@ -6,6 +6,7 @@ import (
"github.com/muety/wakapi/utils"
"html/template"
"io/ioutil"
"net/http"
"path"
"strings"
)
@ -48,3 +49,33 @@ func loadTemplates() {
templates[tplName] = tpl
}
}
func respondAlert(w http.ResponseWriter, error, success, tplName string, status int) {
w.WriteHeader(status)
if tplName == "" {
tplName = "index.tpl.html"
}
templates[tplName].Execute(w, struct {
Error string
Success string
}{Error: error})
}
// TODO: do better
func handleAlerts(w http.ResponseWriter, r *http.Request, tplName string) bool {
if err := r.URL.Query().Get("error"); err != "" {
if err == "unauthorized" {
respondAlert(w, err, "", tplName, http.StatusUnauthorized)
} else {
respondAlert(w, err, "", tplName, http.StatusInternalServerError)
}
return true
}
if success := r.URL.Query().Get("success"); success != "" {
respondAlert(w, "", success, tplName, http.StatusOK)
return true
}
return false
}

View File

@ -20,19 +20,19 @@ const (
)
type SummaryHandler struct {
cummarySrvc *services.SummaryService
summarySrvc *services.SummaryService
config *models.Config
}
func NewSummaryHandler(summaryService *services.SummaryService) *SummaryHandler {
return &SummaryHandler{
cummarySrvc: summaryService,
summarySrvc: summaryService,
config: models.GetConfig(),
}
}
func (h *SummaryHandler) ApiGet(w http.ResponseWriter, r *http.Request) {
summary, err, status := loadUserSummary(r, h.cummarySrvc)
summary, err, status := loadUserSummary(r, h.summarySrvc)
if err != nil {
w.WriteHeader(status)
w.Write([]byte(err.Error()))
@ -53,16 +53,22 @@ func (h *SummaryHandler) Index(w http.ResponseWriter, r *http.Request) {
r.URL.RawQuery = q.Encode()
}
summary, err, status := loadUserSummary(r, h.cummarySrvc)
summary, err, status := loadUserSummary(r, h.summarySrvc)
if err != nil {
w.WriteHeader(status)
w.Write([]byte(err.Error()))
respondAlert(w, err.Error(), "", "summary.tpl.html", status)
return
}
user := r.Context().Value(models.UserKey).(*models.User)
if user == nil {
respondAlert(w, "unauthorized", "", "summary.tpl.html", http.StatusUnauthorized)
return
}
vm := models.SummaryViewModel{
Summary: summary,
LanguageColors: utils.FilterLanguageColors(h.config.LanguageColors, summary),
ApiKey: user.ApiKey,
}
templates["summary.tpl.html"].Execute(w, vm)

View File

@ -196,6 +196,21 @@ function getRandomColor(seed) {
return color
}
function showApiKeyPopup(event) {
const el = document.getElementById('api-key-popup')
el.classList.remove('hidden')
el.classList.add('block')
event.stopPropagation()
}
function copyApiKey(event) {
const el = document.getElementById('api-key-container')
el.select()
el.setSelectionRange(0, 9999)
document.execCommand('copy')
event.stopPropagation()
}
// https://koddsson.com/posts/emoji-favicon/
const favicon = document.querySelector('link[rel=icon]')
if (favicon) {
@ -211,6 +226,17 @@ if (favicon) {
}
}
// Click outside
window.addEventListener('click', function(event) {
if (event.target.classList.contains('popup')) {
return
}
document.querySelectorAll('.popup').forEach(el => {
el.classList.remove('block')
el.classList.add('hidden')
})
})
window.addEventListener('load', function () {
draw()
})

View File

@ -1 +1 @@
1.3.0
1.4.0

View File

@ -4,9 +4,20 @@
<body class="relative bg-gray-800 text-gray-700 p-4 pt-10 flex flex-col min-h-screen max-w-screen-xl mx-auto justify-center">
<div class="hidden flex bg-gray-800 shadow-md z-10 p-2 absolute top-0 right-0 mt-10 mr-8 border border-green-700 rounded popup" id="api-key-popup">
<div class="flex-grow flex flex-col px-2">
<span class="text-xs text-gray-500 mx-1">API Key</span>
<input type="text" class="bg-transparent text-sm text-white mx-1 font-mono" id="api-key-container" readonly value="{{ .ApiKey }}" style="min-width: 330px">
</div>
<div class="flex items-center px-2 border-l border-gray-700">
<button title="Copy to clipboard" onclick="copyApiKey(event)">📋</button>
</div>
</div>
<div class="absolute top-0 right-0 mr-8 mt-10 py-2">
<form action="logout" method="post">
<button type="submit" class="py-1 px-3 rounded border border-green-700 text-white text-sm">Logout</button>
<button type="button" class="mx-1 py-1 px-3 rounded border border-green-700 text-white text-sm" onclick="showApiKeyPopup(event)">🔐</button>
<button type="submit" class="mx-1 py-1 px-3 rounded border border-green-700 text-white text-sm">Logout</button>
</form>
</div>