Пример #1
0
func logout(w http.ResponseWriter, r *http.Request) error {
	session := web.Session(r)
	delete(session.Values, "userId")
	web.FlashInfo(r, "You have been logged out")
	http.Redirect(w, r, "/login", http.StatusFound)
	return nil
}
Пример #2
0
func login(w http.ResponseWriter, r *http.Request) error {
	username := r.FormValue("username")
	password := r.FormValue("password")

	userLog.Info("Log in: %v/%v", username, password)

	query := DB.QueryRow("SELECT id, username, password FROM users WHERE username = $1", username)
	var user User
	err := query.Scan(&user.Id, &user.Username, &user.password)

	if err != nil {
		web.FlashWarning(r, "No such user found")
		http.Redirect(w, r, "/login", http.StatusFound)
		return nil
	}

	if string(user.password) == password {
		session := web.Session(r)
		session.Values["userId"] = user.Id
		web.FlashInfo(r, fmt.Sprintf("Logged in as %v", user.Username))

		if dest, ok := session.Values["loginDestination"]; ok {
			http.Redirect(w, r, dest.(string), http.StatusFound)
		} else {
			http.Redirect(w, r, "/user", http.StatusFound)
		}
		return nil
	}
	web.FlashWarning(r, "Incorrect username or password")
	http.Redirect(w, r, "/login", http.StatusFound)
	return nil
}
Пример #3
0
// AuthenticateOrRedirect asserts that there is a user logged in.  If there
// is not a user logged in, then the user is redirected to the login page and
// the current URL is stored in the session.  Returns true if the user was
// redirected.
func AuthenticateOrRedirect(w http.ResponseWriter, r *http.Request, urlStr string) bool {
	user, err := CurrentUser(r)
	if user == nil || err != nil {
		session := web.Session(r)
		session.Values["loginDestinatation"] = r.URL.String()
		http.Redirect(w, r, urlStr, http.StatusFound)
		return true
	}
	return false
}
Пример #4
0
// CurrentUser returns the currently logged in user.  It attempts to load
// the user from the context first, and if that fails, it reads a userId
// from the session and loads the user, storing it in the context.  If
// there is no userId in the session (user is not authenticated) then nil
// is returned
func CurrentUser(r *http.Request) (*User, error) {
	if user := context.Get(r, userKey); user != nil {
		return user.(*User), nil
	} else {
		session := web.Session(r)
		userId, ok := session.Values["userId"]
		if !ok {
			// The current user is not authenticated....
			return nil, nil
		}

		user, err := LoadUser(userId.(int))
		if err != nil {
			return nil, err
		}
		context.Set(r, userKey, user)
		return user, nil
	}
	return nil, nil
}