Ejemplo n.º 1
0
func LoginAction(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.NotFound(w, r)
		return
	}
	w.Header().Set("content-type", "application/json")

	defer r.Body.Close()
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		OnResponse(w, 201, "用户名或密码错误", nil)
		return
	}

	var dat map[string]interface{}
	err = json.Unmarshal(body, &dat)
	if err != nil {
		OnResponse(w, 201, "用户名或密码错误", nil)
		return
	}

	email := fmt.Sprint(dat["email"])
	password := fmt.Sprint(dat["passwd"])

	hash := md5.New()
	hash.Write([]byte(password))
	password = hex.EncodeToString(hash.Sum(nil))
	// log.Println(email + "   " + password);

	if email == "" || password == "" {
		OnResponse(w, 201, "用户名或密码错误", nil)
		return
	}
	user, err := service.FindUserByEmail(email)
	if err != nil {
		OnResponse(w, 201, "用户名或密码错误", nil)
		return
	}
	if user.Password != password {
		OnResponse(w, 201, "用户名或密码错误", nil)
		return
	}

	// 存入cookie,使用cookie存储
	t := time.Now()
	expires := time.Date(t.Year(), t.Month(), t.Day(), t.Hour()+5, t.Minute(), t.Second(), 0, time.Local)
	cookie := http.Cookie{Name: conf.SESSION_KEY, Value: base64.StdEncoding.EncodeToString([]byte(email)), Path: "/", Expires: expires}
	http.SetCookie(w, &cookie)

	logger.Log("login", "SignIn", "["+email+"]["+time.Unix(time.Now().Unix(), 0).Format("20060102150405")+"]["+
		r.RemoteAddr+"]["+r.UserAgent()+"]["+r.Host+r.RequestURI+"]")

	OnResponse(w, 200, "ok", nil)

}
Ejemplo n.º 2
0
func UserSaveHandler(response http.ResponseWriter, request *http.Request) {

	if !CheckCookie(response, request, "UserSave") {
		http.NotFound(response, request)
		return
	}

	if request.Method == "GET" {
		model := make(map[string]interface{})
		model["title"] = "Sign In"
		ExecuteTemplate(response, "login", model)
		return
	}

	if request.Method != "POST" {
		http.NotFound(response, request)
		return
	}

	defer request.Body.Close()
	body, err := ioutil.ReadAll(request.Body)
	if err != nil {
		OnResponse(response, 401, "请求参数不能为空", nil)
		return
	}

	var dat map[string]interface{}
	err = json.Unmarshal(body, &dat)
	if err != nil {
		OnResponse(response, 402, "JSON解析失败", nil)
		return
	}

	firstName := fmt.Sprint(dat["firstName"])
	lastName := fmt.Sprint(dat["lastName"])
	email := fmt.Sprint(dat["email"])
	password := fmt.Sprint(dat["password"])

	_, e := service.FindUserByEmail(email)
	if e == nil {
		// http.NotFound(response, request);
		OnResponse(response, 201, "用户已存在", nil)
		return
	}

	hash := md5.New()
	hash.Write([]byte(password))
	password = hex.EncodeToString(hash.Sum(nil))

	service.SaveUser(firstName, lastName, email, password)

	OnResponse(response, 200, "ok", nil)
}