aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--cmd/koushin/main.go12
-rw-r--r--conn_pool.go58
-rw-r--r--go.mod5
-rw-r--r--go.sum10
-rw-r--r--public/login.html14
-rw-r--r--server.go155
6 files changed, 248 insertions, 6 deletions
diff --git a/cmd/koushin/main.go b/cmd/koushin/main.go
index cc86467..6e364cb 100644
--- a/cmd/koushin/main.go
+++ b/cmd/koushin/main.go
@@ -1,12 +1,22 @@
package main
import (
+ "fmt"
+ "os"
+
"git.sr.ht/~emersion/koushin"
"github.com/labstack/echo/v4/middleware"
)
func main() {
- e := koushin.New()
+ if len(os.Args) != 2 {
+ fmt.Println("usage: koushin imaps://<host>:<port>")
+ return
+ }
+
+ url := os.Args[1]
+
+ e := koushin.New(url)
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Logger.Fatal(e.Start(":1323"))
diff --git a/conn_pool.go b/conn_pool.go
new file mode 100644
index 0000000..147c022
--- /dev/null
+++ b/conn_pool.go
@@ -0,0 +1,58 @@
+package koushin
+
+import (
+ "crypto/rand"
+ "encoding/base64"
+ "errors"
+
+ imapclient "github.com/emersion/go-imap/client"
+)
+
+func generateToken() (string, error) {
+ b := make([]byte, 32)
+ _, err := rand.Read(b)
+ if err != nil {
+ return "", err
+ }
+ return base64.URLEncoding.EncodeToString(b), nil
+}
+
+var ErrSessionExpired = errors.New("session expired")
+
+// TODO: expiration timer
+type ConnPool struct {
+ // TODO: add synchronization
+ conns map[string]*imapclient.Client
+}
+
+func NewConnPool() *ConnPool {
+ return &ConnPool{
+ conns: make(map[string]*imapclient.Client),
+ }
+}
+
+func (pool *ConnPool) Get(token string) (*imapclient.Client, error) {
+ conn, ok := pool.conns[token]
+ if !ok {
+ return nil, ErrSessionExpired
+ }
+ return conn, nil
+}
+
+func (pool *ConnPool) Put(conn *imapclient.Client) (token string, err error) {
+ for {
+ var err error
+ token, err = generateToken()
+ if err != nil {
+ conn.Logout()
+ return "", err
+ }
+
+ if _, ok := pool.conns[token]; !ok {
+ break
+ }
+ }
+
+ pool.conns[token] = conn
+ return token, nil
+}
diff --git a/go.mod b/go.mod
index 7e8ba30..07d3dac 100644
--- a/go.mod
+++ b/go.mod
@@ -2,4 +2,7 @@ module git.sr.ht/~emersion/koushin
go 1.13
-require github.com/labstack/echo/v4 v4.1.11
+require (
+ github.com/emersion/go-imap v1.0.1
+ github.com/labstack/echo/v4 v4.1.11
+)
diff --git a/go.sum b/go.sum
index 470eea7..bd3e888 100644
--- a/go.sum
+++ b/go.sum
@@ -1,11 +1,18 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
+github.com/emersion/go-imap v1.0.1 h1:J3duplefIrglQtE63hCGYdGLgMjYWqHvkUUEbimbXY8=
+github.com/emersion/go-imap v1.0.1/go.mod h1:MEiDDwwQFcZ+L45Pa68jNGv0qU9kbW+SJzwDpvSfX1s=
+github.com/emersion/go-message v0.10.4-0.20190609165112-592ace5bc1ca/go.mod h1:3h+HsGTCFHmk4ngJ2IV/YPhdlaOcR6hcgqM3yca9v7c=
+github.com/emersion/go-sasl v0.0.0-20190520160400-47d427600317 h1:tYZxAY8nu3JJQKios9f27Sbvbkfm4XHXT476gVtszu0=
+github.com/emersion/go-sasl v0.0.0-20190520160400-47d427600317/go.mod h1:G/dpzLu16WtQpBfQ/z3LYiYJn3ZhKSGWn83fyoyQe/k=
+github.com/emersion/go-textwrapper v0.0.0-20160606182133-d0e65e56babe/go.mod h1:aqO8z8wPrjkscevZJFVE1wXJrLpC5LtJG7fqLOsPb2U=
github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg=
github.com/labstack/echo/v4 v4.1.11 h1:z0BZoArY4FqdpUEl+wlHp4hnr/oSR6MTmQmv8OHSoww=
github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvfxNnFqi74g=
github.com/labstack/gommon v0.3.0 h1:JEeO0bvc78PKdyHxloTKiF8BD5iGrH8T6MSeGvSgob0=
github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=
+github.com/martinlindhe/base36 v0.0.0-20190418230009-7c6542dfbb41/go.mod h1:+AtEs8xrBpCeYgSLoY/aJ6Wf37jtBuR0s35750M27+8=
github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
@@ -30,5 +37,8 @@ golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
+golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
diff --git a/public/login.html b/public/login.html
new file mode 100644
index 0000000..54cb341
--- /dev/null
+++ b/public/login.html
@@ -0,0 +1,14 @@
+{{template "head"}}
+
+<h1>koushin</h1>
+
+<form method="post" action="/login">
+ <p>Username:</p>
+ <input type="text" name="username">
+ <p>Password:</p>
+ <input type="password" name="password">
+ <br><br>
+ <input type="submit" value="Login">
+</form>
+
+{{template "foot"}}
diff --git a/server.go b/server.go
index 21fd0fa..cd03c5d 100644
--- a/server.go
+++ b/server.go
@@ -1,24 +1,171 @@
package koushin
import (
+ "fmt"
"net/http"
+ "net/url"
+ "time"
"github.com/labstack/echo/v4"
+ imapclient "github.com/emersion/go-imap/client"
)
-func New() *echo.Echo {
- e := echo.New()
+const cookieName = "koushin_session"
+
+type Server struct {
+ imap struct {
+ host string
+ tls bool
+ insecure bool
+
+ pool *ConnPool
+ }
+}
+
+func NewServer(imapURL string) (*Server, error) {
+ u, err := url.Parse(imapURL)
+ if err != nil {
+ return nil, err
+ }
+
+ s := &Server{}
+ s.imap.host = u.Host
+ switch u.Scheme {
+ case "imap":
+ // This space is intentionally left blank
+ case "imaps":
+ s.imap.tls = true
+ case "imap+insecure":
+ s.imap.insecure = true
+ default:
+ return nil, fmt.Errorf("unrecognized IMAP URL scheme: %s", u.Scheme)
+ }
+
+ s.imap.pool = NewConnPool()
+ return s, nil
+}
+
+func (s *Server) connectIMAP() (*imapclient.Client, error) {
+ var c *imapclient.Client
var err error
+ if s.imap.tls {
+ c, err = imapclient.DialTLS(s.imap.host, nil)
+ if err != nil {
+ return nil, err
+ }
+ } else {
+ c, err = imapclient.Dial(s.imap.host)
+ if err != nil {
+ return nil, err
+ }
+ if !s.imap.insecure {
+ if err := c.StartTLS(nil); err != nil {
+ c.Close()
+ return nil, err
+ }
+ }
+ }
+
+ return c, err
+}
+
+type context struct {
+ echo.Context
+ server *Server
+ conn *imapclient.Client
+}
+
+var aLongTimeAgo = time.Unix(233431200, 0)
+
+func (c *context) setToken(token string) {
+ cookie := http.Cookie{
+ Name: cookieName,
+ Value: token,
+ HttpOnly: true,
+ // TODO: domain, secure
+ }
+ if token == "" {
+ cookie.Expires = aLongTimeAgo // unset the cookie
+ }
+ c.SetCookie(&cookie)
+}
+
+func handleLogin(ectx echo.Context) error {
+ ctx := ectx.(*context)
+ username := ctx.FormValue("username")
+ password := ctx.FormValue("password")
+ if username != "" && password != "" {
+ conn, err := ctx.server.connectIMAP()
+ if err != nil {
+ return err
+ }
+
+ if err := conn.Login(username, password); err != nil {
+ conn.Logout()
+ return ctx.Render(http.StatusOK, "login.html", nil)
+ }
+
+ token, err := ctx.server.imap.pool.Put(conn)
+ if err != nil {
+ return err
+ }
+ ctx.setToken(token)
+
+ return ctx.Redirect(http.StatusFound, "/")
+ }
+
+ return ctx.Render(http.StatusOK, "login.html", nil)
+}
+
+func New(imapURL string) *echo.Echo {
+ e := echo.New()
+
+ s, err := NewServer(imapURL)
+ if err != nil {
+ e.Logger.Fatal(err)
+ }
+
+ e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(ectx echo.Context) error {
+ ctx := &context{Context: ectx, server: s}
+
+ cookie, err := ctx.Cookie(cookieName)
+ if err == http.ErrNoCookie {
+ return next(ctx)
+ } else if err != nil {
+ return err
+ }
+
+ ctx.conn, err = ctx.server.imap.pool.Get(cookie.Value)
+ if err == ErrSessionExpired {
+ ctx.setToken("")
+ return ctx.Redirect(http.StatusFound, "/login")
+ } else if err != nil {
+ return err
+ }
+
+ return next(ctx)
+ }
+ })
+
e.Renderer, err = loadTemplates()
if err != nil {
e.Logger.Fatal("Failed to load templates:", err)
}
- e.GET("/", func(c echo.Context) error {
- return c.Render(http.StatusOK, "index.html", nil)
+ e.GET("/", func(ectx echo.Context) error {
+ ctx := ectx.(*context)
+ if ctx.conn == nil {
+ return ctx.Redirect(http.StatusFound, "/login")
+ }
+
+ return ctx.Render(http.StatusOK, "index.html", nil)
})
+ e.GET("/login", handleLogin)
+ e.POST("/login", handleLogin)
+
e.Static("/assets", "public/assets")
return e