Example #1
0
func LoginHandler(w http.ResponseWriter, r *http.Request) error {
	// POST validation
	if r.FormValue("Password") == "" || r.FormValue("Username") == "" {
		return util.NewError(nil, "Missing username or password", 400)
	}

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

	// User authentication
	authenticated, err := gen.CheckCredentials(db, r.FormValue("Username"), r.FormValue("Password"))
	if err != nil {
		return err
	}
	if authenticated {
		myCookie, err := util.CreateCookie(r.FormValue("Username"), db, true, true) // This also stores a hashed cookie in the database
		if err != nil {
			return err
		}
		http.SetCookie(w, &myCookie)
		w.WriteHeader(200)
		fmt.Fprint(w, "Logged in as "+r.FormValue("Username"))
		return nil
	} else {
		return util.NewError(nil, "Your username or password was incorrect", 400)
	}
	return nil
}
Example #2
0
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
}