package main import ( "io/ioutil" "log" "net/http" "os" "path" "time" "github.com/alexedwards/scs/v2" "github.com/casbin/casbin" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "git.ofmax.li/iserv/internal/acct" "git.ofmax.li/iserv/internal/auth" "git.ofmax.li/iserv/internal/db/redis" "git.ofmax.li/iserv/internal/fs" "git.ofmax.li/iserv/internal/goog" "git.ofmax.li/iserv/internal/image" "go.ofmax.li/tmpl" ) func serviceConfig() (*oauth2.Config, error) { b, err := ioutil.ReadFile("credentials.json") if err != nil { log.Fatalf("Unable to read client secret file: %v", err) } scopes := []string{ "https://www.googleapis.com/auth/userinfo.email", "openid", } config, err := google.ConfigFromJSON(b, scopes...) return config, err } func main() { connPool := redis.CreatePool("localhost:6379") oauthClientConfig, err := serviceConfig() if err != nil { log.Fatal("failed to load service creds") } renderer, err := tmpl.NewHTMLTmpl("templates") if err != nil { log.Fatal(err) } storagePath, err := os.Getwd() if err != nil { log.Fatal("couldn't find directory to write images to") } sessionManager := scs.New() sessionManager.Lifetime = 24 * time.Hour // Google googService := goog.NewService(oauthClientConfig) // Image imgdb := redis.NewRedisImageRepo(connPool) imageService := image.NewService(imgdb, storagePath, renderer) imageHandler := image.NewHandler(imageService) imageFile := fs.NewHandler(storagePath) // Auth // Auth Enforcer enf := casbin.NewEnforcer("auth_model.ini", "policy.csv") authdb := redis.NewRedisAuthRepo(connPool) authService := auth.NewService(authdb, googService, enf) authHandler := auth.NewHandler(authService, sessionManager) // Acct acctDb := redis.NewAcctRepo(connPool) acctService := acct.NewService(acctDb, authdb, googService) acctHandler := acct.NewHandler(acctService, sessionManager) // Static Files staticFiles := fs.NewHandler(path.Join(storagePath, "static")) r := chi.NewRouter() r.Use(middleware.StripSlashes) r.Use(middleware.Logger) r.Use(sessionManager.LoadAndSave) r.Use(auth.AuthOnly(authService, sessionManager)) r.Get("/a/g", authHandler.OauthCallback) r.Get("/l", authHandler.Login) r.Get("/u/register", acctHandler.Register) r.Get("/i/{fileName}", imageHandler.GetImage) r.Post("/i", imageHandler.PostImage) r.Get("/f/*", imageFile) r.Get("/static/*", staticFiles) log.Print("starting imageserv") log.Fatal(http.ListenAndServe(":8080", r)) }