package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/qor5/x/i18n"
"github.com/qor5/x/login"
"github.com/markbates/goth/providers/google"
"github.com/markbates/goth/providers/twitter"
. "github.com/theplant/htmlgo"
"github.com/theplant/testingutils"
"golang.org/x/text/language"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type User struct {
gorm.Model
login.UserPass
login.OAuthInfo
login.SessionSecure
}
func main() {
var err error
db, err := gorm.Open(sqlite.Open("/tmp/test_login.db"), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
})
if err != nil {
panic(err)
}
if err := db.AutoMigrate(&User{}); err != nil {
panic(err)
}
user := &User{
UserPass: login.UserPass{
Account: "user@example.com",
Password: "123",
},
}
user.EncryptPassword()
db.Create(user)
b := login.New().
DB(db).
UserModel(&User{}).
Secret("123").
OAuthProviders(
&login.Provider{
Goth: google.New(os.Getenv("LOGIN_GOOGLE_KEY"), os.Getenv("LOGIN_GOOGLE_SECRET"), "http://localhost:9500/auth/callback?provider=google"),
Key: "google",
Text: "Login with Google",
Logo: RawHTML(``),
},
&login.Provider{
Goth: twitter.New(os.Getenv("LOGIN_TWITTER_KEY"), os.Getenv("LOGIN_TWITTER_SECRET"), "http://localhost:9500/auth/callback?provider=twitter"),
Key: "twitter",
Text: "Login with Twitter",
Logo: RawHTML(``),
},
).
HomeURLFunc(func(r *http.Request, user interface{}) string {
return "/admin"
}).
NotifyUserOfResetPasswordLinkFunc(func(user interface{}, resetLink string) error {
fmt.Println("#########################################start")
testingutils.PrintlnJson(resetLink)
fmt.Println("#########################################end")
return nil
})
i18nB := i18n.New()
i18nB.SupportLanguages(language.English, language.SimplifiedChinese)
b.I18n(i18nB)
h := http.NewServeMux()
b.Mount(h)
h.Handle("/admin", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "%#+v", login.GetCurrentUser(r))
}))
mux := http.NewServeMux()
mux.Handle("/", login.Authenticate(b)(h))
log.Println("serving at http://localhost:9500")
log.Fatal(http.ListenAndServe(":9500", mux))
}