package front

import (
	"fmt"
	. "jy/mongodbutil"
	. "jy/router"
	. "jy/util"
	"net/http"
	qu "qfw/util"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

func init() {
	front := Router.Group("/")
	{
		front.Static("/front", "./web/templates/front")
		front.Static("/res", "./web/res")
	}
	front.POST("/login", Login)  //登录
	front.GET("/logout", Logout) //注销
}

func Login(c *gin.Context) {
	email := c.PostForm("email")
	pwd := c.PostForm("pwd")
	res, _ := Mgo.FindOne("user", fmt.Sprintf(`{"email":"%s","pwd":"%s"}`, email, Se.EncodeString(pwd)))
	if res != nil && len(*res) > 0 {
		session := sessions.Default(c)
		(*res)["pwd"] = pwd
		(*res)["_id"] = qu.BsonIdToSId((*res)["_id"])
		session.Set("user", res)
		session.Set("username", (*res)["name"])
		session.Save()
		c.JSON(200, gin.H{"checked": true})
	} else {
		c.JSON(200, gin.H{"checked": false})
	}
}
func Logout(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete("user")
	c.Redirect(http.StatusMovedPermanently, "/front/login.html")
}
