Exemple #1
0
func (app *App) handleLogin(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		app.serveFile("login.html").ServeHTTP(w, r)
	case "POST":

		username := r.FormValue("username")
		password := r.FormValue("password")
		if username == "" {
			http.Error(w, "No username provided", http.StatusBadRequest)
			return
		}
		if password == "" {
			http.Error(w, "No password provided", http.StatusBadRequest)
			return
		}

		tx, err := app.db.Begin()
		if err != nil {
			app.dbError(w, r, err)
			return
		}
		defer tx.Rollback()

		user, err := db.GetUser(tx, username)
		if err != nil {
			if db.IsNotFound(err) {
				http.Error(w, "User not found", http.StatusNotFound)
			} else {
				app.dbError(w, r, err)
			}
			return
		}
		if phash.Verify(password, user.Password) {
			u := &User{Id: user.Id, Name: user.Name}
			app.setUser(r, w, u)
			w.WriteHeader(http.StatusOK)
		} else {
			http.Error(w, "Invalid username passsword combination.", http.StatusBadRequest)
		}

	default:
		http.Error(w, "I only respond to GET and POSTs", http.StatusNotImplemented)
	}
}
Exemple #2
0
func (app *App) handleVerifyPassword(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		// user should already be logged in, we're just validating the password
		password := r.FormValue("password")
		sessionUser, ok := app.getUser(r)

		if !ok {
			http.Error(w, "No user logged in", http.StatusBadRequest)
			return
		}

		tx, err := app.db.Begin()
		if err != nil {
			app.dbError(w, r, err)
			return
		}
		defer tx.Rollback()

		user, err := db.GetUser(tx, sessionUser.Name)
		if err != nil {
			if db.IsNotFound(err) {
				http.Error(w, "User not found", http.StatusNotFound)
			} else {
				app.dbError(w, r, err)
			}
			return
		}

		if password == "" {
			http.Error(w, "No password provided", http.StatusBadRequest)
			return
		}

		if phash.Verify(password, user.Password) {
			w.WriteHeader(http.StatusOK)
		} else {
			http.Error(w, "Invalid username passsword combination.", http.StatusBadRequest)
		}

	default:
		http.Error(w, "I only respond to POSTs", http.StatusNotImplemented)
	}
}