Beispiel #1
0
// ProtectedHandler handles a request towards a protected resource,
// expects an authentication token to check against database
func ProtectedHandler(w http.ResponseWriter, r *http.Request) {
	authHeader := r.Header.Get("Authorization")
	usr, err := auth.TokenAuth(DB, authHeader)
	if err != nil {
		Error.Printf("error: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if usr == "" {
		http.Error(w, "user not logged in", http.StatusForbidden)
		return
	}
	utils.WriteHeader(w, http.StatusOK, utils.JSONContent)
	err = utils.WriteJSON(w, map[string]string{"content": "protected"})
	if err != nil {
		Error.Printf("error: %v", err)
		http.Error(w, "json encoding error", http.StatusInternalServerError)
		return
	}
}
Beispiel #2
0
// LoginHandler is the handler function in which login requests are routed to
// http://www.alexedwards.net/blog/a-recap-of-request-handling
func LoginHandler(w http.ResponseWriter, r *http.Request) {
	userID, password, err := getBasicAuth(r)
	if err != nil {
		Error.Printf("error: %v", err)
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	// check against data in database
	ok, err := auth.BasicAuth(DB, userID, password)
	if err != nil {
		Error.Printf("error: %v", err)
		// write error response
		http.Error(w, "internal database error", http.StatusInternalServerError)
		return
	}
	if ok == false {
		http.Error(w, "invalid username and password combination",
			http.StatusForbidden)
		return
	}
	// generate a token for the user
	token, err := auth.LoginUser(DB, userID, expiry)
	if err != nil {
		Error.Printf("error: %v", err)
		// write error response
		http.Error(w, "internal database error", http.StatusInternalServerError)
		return
	}

	//write status and token to response
	utils.WriteHeader(w, http.StatusOK, utils.JSONContent)
	err = utils.WriteJSON(w, map[string]string{"token": token})
	if err != nil {
		Error.Printf("error: %v", err)
		http.Error(w, "json encoding error", http.StatusInternalServerError)
		return
	}
}