예제 #1
0
파일: 5sur.go 프로젝트: ErikBrown/5sur
func LoginFormHandler(w http.ResponseWriter, r *http.Request) error {
	db, err := util.OpenDb()
	if err != nil {
		return err
	}
	defer db.Close()

	_, userId, _, err := util.CheckCookie(r, db) // return "" if not logged in
	if err != nil {
		return err
	}
	if userId != 0 {
		http.Redirect(w, r, "https://5sur.com/", 303)
		return nil
	}

	userIp := ""
	if ipProxy := r.Header.Get("X-Real-IP"); len(ipProxy) > 0 {
		userIp = ipProxy
	} else {
		userIp, _, _ = net.SplitHostPort(r.RemoteAddr)
	}

	attempts, err := gen.CheckAttempts(db, userIp)
	if err != nil {
		return err
	}

	var script, captcha template.HTML
	if attempts > 2 {
		script = `<script src='https://www.google.com/recaptcha/api.js'></script>`
		captcha = `<div class="g-recaptcha" data-sitekey="6LfejAATAAAAAK1DA4l33OntwJy9LZz1GK3F2Egr"></div>`
	}
	registerData := &gen.LoginHTML{
		Title:   "Ingresar",
		Script:  script,
		Captcha: captcha,
	}
	err = templates.ExecuteTemplate(w, "login.html", registerData)
	if err != nil {
		return util.NewError(err, "No se cargó la página", 500)
	}
	return nil
}
예제 #2
0
파일: 5sur.go 프로젝트: ErikBrown/5sur
func LoginHandler(w http.ResponseWriter, r *http.Request) error {
	// POST validation
	if r.FormValue("Password") == "" || r.FormValue("Username") == "" {
		return util.NewError(nil, "Falta nombre de usuario o contraseña", 400)
	}

	// Database initialization
	db, err := util.OpenDb()
	if err != nil {
		return err
	}
	defer db.Close()

	userIp := ""
	if ipProxy := r.Header.Get("X-Real-IP"); len(ipProxy) > 0 {
		userIp = ipProxy
	} else {
		userIp, _, _ = net.SplitHostPort(r.RemoteAddr)
	}

	// Check for captcha if login attempts > 2
	attempts, err := gen.CheckAttempts(db, userIp)
	if err != nil {
		return err
	}

	if attempts > 2 {
		human, err := gen.CheckCaptcha(r.FormValue("g-recaptcha-response"), userIp)
		if err != nil {
			return err
		}
		if !human {
			return util.NewError(nil, "Captcha invalido", 400)
		}
	}

	// User authentication
	authenticated, err := gen.CheckCredentials(db, r.FormValue("Username"), r.FormValue("Password"))
	if err != nil {
		return err
	}
	if authenticated {
		persistent := false
		if r.FormValue("Persistent") == "true" {
			persistent = true
		}
		myCookie, err := util.CreateCookie(r.FormValue("Username"), db, persistent, false) // This also stores a hashed cookie in the database
		if err != nil {
			return err
		}
		http.SetCookie(w, &myCookie)
		http.Redirect(w, r, "https://5sur.com/", 303)
		return nil
	} else {
		err = gen.UpdateLoginAttempts(db, userIp)
		if err != nil {
			return err
		}
		return util.NewError(nil, "Nombre de usuario o contraseña incorrecto", 400)
	}
	return nil
}