arimelody.me/admin/http.go

259 lines
7.4 KiB
Go
Raw Normal View History

package admin
import (
"context"
"fmt"
"html/template"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"arimelody.me/arimelody.me/discord"
"arimelody.me/arimelody.me/global"
musicModel "arimelody.me/arimelody.me/music/model"
)
func Handler() http.Handler {
mux := http.NewServeMux()
mux.Handle("/login", LoginHandler())
mux.Handle("/logout", MustAuthorise(LogoutHandler()))
mux.Handle("/static/", http.StripPrefix("/static", staticHandler()))
mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
session := GetSession(r)
if session == nil {
http.Redirect(w, r, "/admin/login", http.StatusFound)
return
}
type IndexData struct {
Releases []musicModel.Release
Artists []musicModel.Artist
}
serveTemplate("index.html", IndexData{
Releases: global.Releases,
Artists: global.Artists,
}).ServeHTTP(w, r)
}))
return mux
}
func MustAuthorise(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := GetSession(r)
if session == nil {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), "session", session)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func GetSession(r *http.Request) *Session {
// TODO: remove later- this bypasses auth!
return &Session{}
var token = ""
// is the session token in context?
var ctx_session = r.Context().Value("session")
if ctx_session != nil {
token = ctx_session.(string)
}
// okay, is it in the auth header?
if token == "" {
if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
token = r.Header.Get("Authorization")[7:]
}
}
// finally, is it in the cookie?
if token == "" {
cookie, err := r.Cookie("token")
if err != nil {
return nil
}
token = cookie.Value
}
var session *Session = nil
for _, s := range sessions {
if s.Expires.Before(time.Now()) {
// expired session. remove it from the list!
new_sessions := []*Session{}
for _, ns := range sessions {
if ns.Token == s.Token {
continue
}
new_sessions = append(new_sessions, ns)
}
sessions = new_sessions
continue
}
if s.Token == token {
session = s
break
}
}
return session
}
func LoginHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if discord.CREDENTIALS_PROVIDED && ADMIN_ID_DISCORD == "" {
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
code := r.URL.Query().Get("code")
if code == "" {
serveTemplate("login.html", discord.REDIRECT_URI).ServeHTTP(w, r)
return
}
auth_token, err := discord.GetOAuthTokenFromCode(code)
if err != nil {
fmt.Printf("Failed to retrieve discord access token: %s\n", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
discord_user, err := discord.GetDiscordUserFromAuth(auth_token)
if err != nil {
fmt.Printf("Failed to retrieve discord user information: %s\n", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if discord_user.Id != ADMIN_ID_DISCORD {
// TODO: unauthorized user; revoke the token
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
// login success!
session := createSession(discord_user.Username, time.Now().Add(24 * time.Hour))
sessions = append(sessions, &session)
cookie := http.Cookie{}
cookie.Name = "token"
cookie.Value = session.Token
cookie.Expires = time.Now().Add(24 * time.Hour)
// cookie.Secure = true
cookie.HttpOnly = true
cookie.Path = "/"
http.SetCookie(w, &cookie)
w.WriteHeader(http.StatusOK)
w.Header().Add("Content-Type", "text/html")
w.Write([]byte(
"<!DOCTYPE html><html><head>"+
"<meta http-equiv=\"refresh\" content=\"5;url=/admin/\" />"+
"</head><body>"+
"Logged in successfully. "+
"You should be redirected to <a href=\"/admin/\">/admin/</a> in 5 seconds."+
"</body></html>"),
)
})
}
func LogoutHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.NotFound(w, r)
return
}
token := r.Context().Value("token").(string)
if token == "" {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
// remove this session from the list
sessions = func (token string) []*Session {
new_sessions := []*Session{}
for _, session := range sessions {
new_sessions = append(new_sessions, session)
}
return new_sessions
}(token)
w.WriteHeader(http.StatusOK)
w.Write([]byte(
"<meta http-equiv=\"refresh\" content=\"5;url=/\" />"+
"Logged out successfully. "+
"You should be redirected to <a href=\"/\">/</a> in 5 seconds."),
)
})
}
func serveTemplate(page string, data any) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lp_layout := filepath.Join("views", "admin", "layout.html")
lp_prideflag := filepath.Join("views", "prideflag.html")
fp := filepath.Join("views", "admin", filepath.Clean(page))
info, err := os.Stat(fp)
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
return
}
}
if info.IsDir() {
http.NotFound(w, r)
return
}
template, err := template.ParseFiles(lp_layout, lp_prideflag, fp)
if err != nil {
fmt.Printf("Error parsing template files: %s\n", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
err = template.ExecuteTemplate(w, "layout.html", data)
if err != nil {
fmt.Printf("Error executing template: %s\n", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
})
}
func staticHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
info, err := os.Stat(filepath.Join("admin", "static", filepath.Clean(r.URL.Path)))
// does the file exist?
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
return
}
}
// is thjs a directory? (forbidden)
if info.IsDir() {
http.NotFound(w, r)
return
}
http.FileServer(http.Dir(filepath.Join("admin", "static"))).ServeHTTP(w, r)
})
}