func ListRepos(server Server) Repos { var repos Repos client := http.Client{} r, err := http.NewRequest("GET", server.Url+"/repositories/", nil) Login(server, r) resp, err := client.Do(r) if err != nil { logger.Log(err.Error(), logger.WARN) } body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1048576)) if err != nil { logger.Log(err.Error(), logger.ERROR) } if err := resp.Body.Close(); err != nil { logger.Log(err.Error(), logger.ERROR) } if err := json.Unmarshal(body, &repos); err != nil { return nil logger.Log(err.Error(), logger.WARN) } return repos }
func ServerCreate(w http.ResponseWriter, r *http.Request) { if authentication.IsAllowed(w, r) { var server pulp.Server body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576)) if err != nil { logger.Log("could not read POST body, Error: "+err.Error(), logger.ERROR) } if err := r.Body.Close(); err != nil { logger.Log("could not close POST body, Error: "+err.Error(), logger.ERROR) } if err := json.Unmarshal(body, &server); err != nil { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(422) // unprocessable entity if err := json.NewEncoder(w).Encode(err); err != nil { logger.Log("could not json/encode error, Error: "+err.Error(), logger.ERROR) } } session, collection := db.InitServerCollection() defer session.Close() server.Added = time.Now() err = collection.Insert(server) if err != nil { logger.Log("could not insert server to DB, Error: "+err.Error(), logger.ERROR) } w.Header().Set("Content-Type", "application/json; charset=UTF=8") w.WriteHeader(http.StatusCreated) if err := json.NewEncoder(w).Encode(server); err != nil { panic(err) } } }
func Connect() *mgo.Session { url := "mongodb://" + config.Settings.DbUser + ":" + config.Settings.DbPassword + "@" + config.Settings.DbHost + ":" + config.Settings.DbPort + "/" + config.Settings.DbName logger.Log("Connecting to "+url, logger.INFO) session, err := mgo.Dial(url) if err != nil { logger.Log("Connection to mongodb failed, Error: "+err.Error(), logger.ERROR) panic(err) } return session }
func init() { // First load defaults loadDefaultConfig() // Second load config file configFile, err := os.Open("config.json") if err != nil { logger.Log("Could not load configuration file - Loading defaults, Error: "+err.Error(), logger.ERROR) } else { jsonParser := json.NewDecoder(configFile) if err = jsonParser.Decode(&Settings); err != nil { logger.Log("Parsing config file config.json failed, Error:"+err.Error(), logger.ERROR) } } // Third load config from flags setFlags() logger.Log("API Version: "+Settings.ApiVersion, logger.INFO) }
func init() { signBytes, err := ioutil.ReadFile(config.Settings.PrivKeyPath) if err != nil { logger.Log("Reading private Key File "+config.Settings.PrivKeyPath+" failed, Error: "+err.Error(), logger.ERROR) } signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes) if err != nil { logger.Log("Parsing private Key File failed, Error: "+err.Error(), logger.ERROR) } verifyBytes, err := ioutil.ReadFile(config.Settings.PubKeyPath) if err != nil { logger.Log("Reading public Key File "+config.Settings.PubKeyPath+" failed, Error: "+err.Error(), logger.ERROR) } verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes) if err != nil { logger.Log("Parsing public Key File failed, Error: "+err.Error(), logger.ERROR) } }
func ServerShow(w http.ResponseWriter, r *http.Request) { oid := getOID("serverId", r) session, collection := db.InitServerCollection() defer session.Close() server := pulp.Server{} db.SearchOne(bson.M{"_id": oid}, collection, &server) if err := json.NewEncoder(w).Encode(server); err != nil { logger.Log("could not encode server struct, Error: "+err.Error(), logger.ERROR) } }
func ServerIndex(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) session, collection := db.InitServerCollection() defer session.Close() servers := pulp.Servers{} db.SearchAll(bson.M{}, collection, &servers) if err := json.NewEncoder(w).Encode(servers); err != nil { logger.Log("could not encode servers struct, Error: "+err.Error(), logger.ERROR) } }
func ServerDelete(w http.ResponseWriter, r *http.Request) { if authentication.IsAllowed(w, r) { oid := getOID("serverId", r) session, collection := db.InitServerCollection() defer session.Close() err := collection.Remove(bson.M{"_id": oid}) if err != nil { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusInternalServerError) if err := json.NewEncoder(w).Encode(err); err != nil { logger.Log("could not json/encode error, Error: "+err.Error(), logger.ERROR) } } } }
func CreateTokenString(user string) (string, error) { // create a signer for rsa256 t := jwt.New(jwt.GetSigningMethod("RS256")) // set our claims t.Claims["AccesToken"] = "level1" t.Claims["CustomUserInfo"] = struct { Name string Role string }{user, "admin"} logger.Log("Created claims", logger.DEBUG) // set expire time t.Claims["exp"] = time.Now().Add(time.Hour * time.Duration(config.Settings.Tokenexpiration)).Unix() return t.SignedString(signKey) }
func NewRouter() *mux.Router { router := mux.NewRouter().StrictSlash(true) logger.Log("Router API Version: "+config.Settings.ApiVersion, logger.INFO) routes := SetRoutes() for _, route := range routes { var handler http.Handler handler = route.HandlerFunc handler = logger.Logger(handler, route.Name) router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(handler) } return router }
func IsAllowed(w http.ResponseWriter, r *http.Request) bool { logger.Log("Checking whether admintoken is set", logger.DEBUG) client_token := r.Header.Get("admintoken") if client_token == "" { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusForbidden) json.NewEncoder(w).Encode(map[string]string{"error": "token not set"}) logger.Log("Token 'admintoken' not set", logger.WARN) return false } // validate the token token, err := jwt.Parse(client_token, func(token *jwt.Token) (interface{}, error) { return verifyKey, nil }) switch err.(type) { case nil: //no error if !token.Valid { // may be invalid w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(map[string]string{"error": "token is invalid"}) logger.Log("Token is invalid", logger.WARN) return false } return true case *jwt.ValidationError: // something was wrong during the validation vErr := err.(*jwt.ValidationError) switch vErr.Errors { case jwt.ValidationErrorExpired: w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(map[string]string{"error": "token expired"}) logger.Log("Token expired", logger.WARN) return false default: w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(map[string]string{"error": "error while parsing token "}) logger.Log("Error while parsing token: "+token.Raw, logger.WARN) return false } default: // something else went wrong w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusInternalServerError) json.NewEncoder(w).Encode(map[string]string{"error": "something went wrong"}) logger.Log("Something with this token is wrong: "+token.Raw, logger.ERROR) return false } }
// Handles Authentication requests func AuthHandler(w http.ResponseWriter, r *http.Request) { // has to be POST if r.Method != "POST" { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusBadRequest) return } var user AdminUser json.NewDecoder(r.Body).Decode(&user) logger.Log("Authenticate: user["+user.Username+"] pass["+user.Password+"]", logger.INFO) if authentication.Authenticate(user.Username, user.Password) { logger.Log("Authenticating user["+user.Username+"] successful", logger.INFO) } else { logger.Log("Authenticating user["+user.Username+"] not successful", logger.WARN) w.WriteHeader(http.StatusForbidden) return } tokenString, err := authentication.CreateTokenString(user.Username) logger.Log("Created token string", logger.DEBUG) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, "Sorry error while Signing Key") logger.Log("Token Signing error: %s"+err.Error(), logger.ERROR) return } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) logger.Log("Sending back token: "+tokenString, logger.DEBUG) if err := json.NewEncoder(w).Encode(map[string]string{"token": tokenString}); err != nil { logger.Log("Sending token unsuccessful, Error: "+err.Error(), logger.ERROR) } }
func fatal(err error) { if err != nil { logger.Log(err.Error(), logger.ERROR) } }
func SearchAll(search bson.M, collection *mgo.Collection, result interface{}) { err := collection.Find(search).All(result) if err != nil { logger.Log("MongoDB search failed, Error: "+err.Error(), logger.ERROR) } }