github.com/fanux/shipyard@v0.0.0-20161009071005-6515ce223235/controller/api/accounts.go (about)

     1  package api
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  
     7  	log "github.com/Sirupsen/logrus"
     8  	"github.com/gorilla/mux"
     9  	"github.com/shipyard/shipyard/auth"
    10  )
    11  
    12  func (a *Api) accounts(w http.ResponseWriter, r *http.Request) {
    13  	w.Header().Set("content-type", "application/json")
    14  
    15  	accounts, err := a.manager.Accounts()
    16  	if err != nil {
    17  		http.Error(w, err.Error(), http.StatusInternalServerError)
    18  		return
    19  	}
    20  	if err := json.NewEncoder(w).Encode(accounts); err != nil {
    21  		http.Error(w, err.Error(), http.StatusInternalServerError)
    22  		return
    23  	}
    24  }
    25  
    26  func (a *Api) saveAccount(w http.ResponseWriter, r *http.Request) {
    27  	var account *auth.Account
    28  	if err := json.NewDecoder(r.Body).Decode(&account); err != nil {
    29  		http.Error(w, err.Error(), http.StatusInternalServerError)
    30  		return
    31  	}
    32  
    33  	if err := a.manager.SaveAccount(account); err != nil {
    34  		log.Errorf("error saving account: %s", err)
    35  		http.Error(w, err.Error(), http.StatusInternalServerError)
    36  		return
    37  	}
    38  
    39  	log.Debugf("updated account: name=%s", account.Username)
    40  	w.WriteHeader(http.StatusNoContent)
    41  }
    42  
    43  func (a *Api) account(w http.ResponseWriter, r *http.Request) {
    44  	vars := mux.Vars(r)
    45  	username := vars["username"]
    46  
    47  	account, err := a.manager.Account(username)
    48  	if err != nil {
    49  		log.Errorf("error deleting account: %s", err)
    50  		http.Error(w, err.Error(), http.StatusInternalServerError)
    51  		return
    52  	}
    53  
    54  	if err := json.NewEncoder(w).Encode(account); err != nil {
    55  		http.Error(w, err.Error(), http.StatusInternalServerError)
    56  		return
    57  	}
    58  }
    59  func (a *Api) deleteAccount(w http.ResponseWriter, r *http.Request) {
    60  	vars := mux.Vars(r)
    61  	username := vars["username"]
    62  
    63  	account, err := a.manager.Account(username)
    64  	if err != nil {
    65  		log.Errorf("error deleting account: %s", err)
    66  		http.Error(w, err.Error(), http.StatusInternalServerError)
    67  		return
    68  	}
    69  	if err := a.manager.DeleteAccount(account); err != nil {
    70  		log.Errorf("error deleting account: %s", err)
    71  		http.Error(w, err.Error(), http.StatusInternalServerError)
    72  		return
    73  	}
    74  
    75  	log.Infof("deleted account: username=%s id=%s", account.Username, account.ID)
    76  	w.WriteHeader(http.StatusNoContent)
    77  }