shiori/cmd/serve.go

274 lines
6.8 KiB
Go
Raw Normal View History

2018-02-11 22:00:56 +08:00
package cmd
import (
2018-02-22 17:48:36 +08:00
"crypto/rand"
2018-02-11 22:00:56 +08:00
"encoding/json"
"fmt"
2018-02-12 22:06:53 +08:00
"github.com/RadhiFadlillah/shiori/model"
2018-02-22 17:48:36 +08:00
"github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
2018-02-11 22:00:56 +08:00
"github.com/julienschmidt/httprouter"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
2018-02-22 17:48:36 +08:00
"golang.org/x/crypto/bcrypt"
2018-02-17 22:49:16 +08:00
"html/template"
2018-02-11 22:00:56 +08:00
"net/http"
fp "path/filepath"
"strings"
2018-02-22 17:48:36 +08:00
"time"
2018-02-11 22:00:56 +08:00
)
var (
2018-02-22 17:48:36 +08:00
jwtKey []byte
2018-02-11 22:00:56 +08:00
serveCmd = &cobra.Command{
Use: "serve",
Short: "Serve web app for managing bookmarks.",
Long: "Run a simple annd performant web server which serves the site for managing bookmarks." +
"If --port flag is not used, it will use port 8080 by default.",
Run: func(cmd *cobra.Command, args []string) {
2018-02-22 17:48:36 +08:00
// Create JWT key
jwtKey = make([]byte, 32)
_, err := rand.Read(jwtKey)
if err != nil {
cError.Println("Failed generating key for token")
return
}
// Create router
2018-02-11 22:00:56 +08:00
router := httprouter.New()
router.GET("/js/*filepath", serveFiles)
router.GET("/css/*filepath", serveFiles)
router.GET("/webfonts/*filepath", serveFiles)
2018-02-17 22:49:16 +08:00
2018-02-22 17:48:36 +08:00
router.GET("/", serveIndexPage)
router.GET("/login", serveLoginPage)
router.GET("/bookmark/:id", serveBookmarkCache)
router.POST("/api/login", apiLogin)
2018-02-11 22:00:56 +08:00
router.GET("/api/bookmarks", apiGetBookmarks)
2018-02-12 22:06:53 +08:00
router.POST("/api/bookmarks", apiInsertBookmarks)
2018-02-13 17:14:08 +08:00
router.PUT("/api/bookmarks", apiUpdateBookmarks)
2018-02-17 16:51:43 +08:00
router.DELETE("/api/bookmarks", apiDeleteBookmarks)
2018-02-12 22:06:53 +08:00
// Route for panic
2018-02-22 17:48:36 +08:00
router.PanicHandler = func(w http.ResponseWriter, r *http.Request, arg interface{}) {
http.Error(w, fmt.Sprint(arg), 500)
}
2018-02-11 22:00:56 +08:00
2018-02-22 17:51:10 +08:00
port, _ := cmd.Flags().GetInt("port")
url := fmt.Sprintf(":%d", port)
2018-02-11 22:00:56 +08:00
logrus.Infoln("Serve shiori in", url)
logrus.Fatalln(http.ListenAndServe(url, router))
},
}
)
func init() {
2018-02-22 17:51:10 +08:00
serveCmd.Flags().IntP("port", "p", 8080, "Port that used by server")
2018-02-11 22:00:56 +08:00
rootCmd.AddCommand(serveCmd)
}
func serveFiles(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
filepath := r.URL.Path
filepath = strings.TrimPrefix(filepath, "/")
filepath = fp.Join("view", filepath)
http.ServeFile(w, r, filepath)
}
2018-02-22 17:48:36 +08:00
func serveIndexPage(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// Check token
err := checkToken(r)
if err != nil {
redirectPage(w, r, "/login")
return
}
filepath := fp.Join("view", "index.html")
http.ServeFile(w, r, filepath)
}
func serveLoginPage(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
filepath := fp.Join("view", "login.html")
http.ServeFile(w, r, filepath)
}
func serveBookmarkCache(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// Read param in URL
id := ps.ByName("id")
// Read bookmarks
2018-02-22 21:45:43 +08:00
bookmarks, err := DB.GetBookmarks(true, id)
2018-02-22 17:48:36 +08:00
checkError(err)
if len(bookmarks) == 0 {
panic(fmt.Errorf("No bookmark with matching index"))
}
// Read template
templates, err := template.New("content.html").ParseFiles("view/content.html")
checkError(err)
err = templates.ExecuteTemplate(w, "content.html", &bookmarks[0])
checkError(err)
}
func apiLogin(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// Decode request
var request model.LoginRequest
err := json.NewDecoder(r.Body).Decode(&request)
checkError(err)
// Get account data from database
accounts, err := DB.GetAccounts(request.Username, true)
if err != nil || len(accounts) == 0 {
panic(fmt.Errorf("Account is not exist"))
}
// Compare password with database
account := accounts[0]
err = bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(request.Password))
if err != nil {
panic(fmt.Errorf("Username and password doesn't match"))
}
// Calculate expiration time
nbf := time.Now()
exp := time.Now().Add(12 * time.Hour)
if request.Remember {
exp = time.Now().Add(7 * 24 * time.Hour)
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"nbf": nbf.Unix(),
"exp": exp.Unix(),
"sub": account.ID,
})
tokenString, err := token.SignedString(jwtKey)
checkError(err)
// Return token
fmt.Fprint(w, tokenString)
}
2018-02-11 22:00:56 +08:00
func apiGetBookmarks(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
2018-02-22 17:48:36 +08:00
// Check token
err := checkAPIToken(r)
checkError(err)
// Fetch all bookmarks
2018-02-22 21:45:43 +08:00
bookmarks, err := DB.GetBookmarks(false)
2018-02-12 22:06:53 +08:00
checkError(err)
2018-02-11 22:00:56 +08:00
2018-02-12 22:06:53 +08:00
err = json.NewEncoder(w).Encode(&bookmarks)
checkError(err)
}
func apiInsertBookmarks(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
2018-02-22 17:48:36 +08:00
// Check token
err := checkAPIToken(r)
checkError(err)
2018-02-12 22:06:53 +08:00
// Decode request
request := model.Bookmark{}
2018-02-22 17:48:36 +08:00
err = json.NewDecoder(r.Body).Decode(&request)
2018-02-12 22:06:53 +08:00
checkError(err)
2018-02-11 22:00:56 +08:00
2018-02-12 22:06:53 +08:00
// Save bookmark
tags := make([]string, len(request.Tags))
for i, tag := range request.Tags {
tags[i] = tag.Name
2018-02-11 22:00:56 +08:00
}
2018-02-12 22:06:53 +08:00
book, err := addBookmark(request.URL, request.Title, request.Excerpt, tags, false)
2018-02-11 22:00:56 +08:00
checkError(err)
2018-02-12 22:06:53 +08:00
// Return new saved result
err = json.NewEncoder(w).Encode(&book)
2018-02-11 22:00:56 +08:00
checkError(err)
}
2018-02-13 17:14:08 +08:00
func apiUpdateBookmarks(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
2018-02-22 17:48:36 +08:00
// Check token
err := checkAPIToken(r)
checkError(err)
2018-02-13 17:14:08 +08:00
// Decode request
request := model.Bookmark{}
2018-02-22 17:48:36 +08:00
err = json.NewDecoder(r.Body).Decode(&request)
2018-02-13 17:14:08 +08:00
checkError(err)
// Convert tags and ID
id := []string{fmt.Sprintf("%d", request.ID)}
tags := make([]string, len(request.Tags))
for i, tag := range request.Tags {
tags[i] = tag.Name
}
// Update bookmark
bookmarks, err := updateBookmarks(id, request.URL, request.Title, request.Excerpt, tags, false)
checkError(err)
// Return new saved result
err = json.NewEncoder(w).Encode(&bookmarks[0])
checkError(err)
}
2018-02-14 12:41:43 +08:00
func apiDeleteBookmarks(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
2018-02-22 17:48:36 +08:00
// Check token
err := checkAPIToken(r)
checkError(err)
2018-02-14 12:41:43 +08:00
// Decode request
2018-02-17 16:51:43 +08:00
request := []string{}
2018-02-22 17:48:36 +08:00
err = json.NewDecoder(r.Body).Decode(&request)
2018-02-17 16:51:43 +08:00
checkError(err)
2018-02-14 12:41:43 +08:00
// Delete bookmarks
2018-02-17 16:51:43 +08:00
_, _, err = DB.DeleteBookmarks(request...)
2018-02-14 12:41:43 +08:00
checkError(err)
2018-02-17 16:51:43 +08:00
fmt.Fprint(w, request)
2018-02-14 12:41:43 +08:00
}
2018-02-17 22:49:16 +08:00
2018-02-22 17:48:36 +08:00
func checkToken(r *http.Request) error {
tokenCookie, err := r.Cookie("token")
if err != nil {
return fmt.Errorf("Token is not exist")
}
2018-02-17 22:49:16 +08:00
2018-02-22 17:48:36 +08:00
token, err := jwt.Parse(tokenCookie.Value, jwtKeyFunc)
if err != nil {
return err
}
2018-02-17 22:49:16 +08:00
2018-02-22 17:48:36 +08:00
claims := token.Claims.(jwt.MapClaims)
return claims.Valid()
}
func checkAPIToken(r *http.Request) error {
token, err := request.ParseFromRequest(r, request.AuthorizationHeaderExtractor, jwtKeyFunc)
if err != nil {
return err
2018-02-17 22:49:16 +08:00
}
2018-02-22 17:48:36 +08:00
claims := token.Claims.(jwt.MapClaims)
return claims.Valid()
}
2018-02-17 22:49:16 +08:00
2018-02-22 17:48:36 +08:00
func jwtKeyFunc(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method")
}
return jwtKey, nil
}
func redirectPage(w http.ResponseWriter, r *http.Request, url string) {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
http.Redirect(w, r, url, 301)
2018-02-17 22:49:16 +08:00
}