Advertisement
Guest User

Untitled

a guest
Dec 27th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.64 KB | None | 0 0
  1. package controllers
  2.  
  3. import (
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "log"
  9. "net/http"
  10. "os"
  11. "strconv"
  12. "time"
  13.  
  14. "github.com/gorilla/mux"
  15. "github.com/jinzhu/gorm"
  16. _ "github.com/jinzhu/gorm/dialects/postgres"
  17. _ "github.com/lib/pq"
  18. _ "gitlab.torq.trans.apps.ge.com/503081542/k-auth-api/models"
  19. "gitlab.torq.trans.apps.ge.com/torq/torq-auth-api/models"
  20. )
  21.  
  22. var err error
  23.  
  24. type API struct {
  25. Database *gorm.DB
  26. Router *mux.Router
  27. }
  28.  
  29. func (api *API) Initialize(opts string) {
  30.  
  31. // Initialize DB
  32.  
  33. var driver = "postgres"
  34. var host = os.Getenv("DB_HOST")
  35. var dbname = os.Getenv("DB_NAME")
  36. var user = os.Getenv("DB_USER")
  37. var password = os.Getenv("DB_PASSWORD")
  38. var port = os.Getenv("DB_PORT")
  39. var conn = fmt.Sprintf("host=%v dbname=%v user=%v password=%v port=%v sslmode=disable", host, dbname, user, password, port)
  40. api.Database, err = gorm.Open(driver, conn)
  41.  
  42. if err != nil {
  43. log.Print("failed to connect to the database")
  44. log.Fatal(err)
  45. }
  46.  
  47. fmt.Println("Connection established")
  48. log.Printf("Postgres started at %s PORT", port)
  49.  
  50. // MODELS
  51.  
  52. type Application struct {
  53. ID string `json:"id" gorm:"primary_key"`
  54. AccessId int64
  55. CreatedAt time.Time `json:"-"`
  56. UpdatedAt time.Time `json:"-"`
  57. Name string `json:"name"`
  58. Ci string `json:"ci"`
  59. }
  60. type Cloud struct {
  61. ID string `json:"id" gorm:"primary_key"`
  62. Name string `json:"name"`
  63. }
  64. type Cluster struct {
  65. ID string `json:"id" gorm:"primary_key"`
  66. CreatedAt time.Time `json:"-"`
  67. UpdatedAt time.Time `json:"-"`
  68. ApplicationID string `json:"application_id"`
  69. VPCID string `json:"vpc_id"`
  70. Name string `json:"name"`
  71. ServiceAcctToken string `json:"service_acct_token"`
  72. ClusterHostname string `json:"cluster_hostname"`
  73. DashboardHostname string `json:"dashboard_hostname"`
  74. }
  75. type ClusterRole struct {
  76. ID string `json:"id" gorm:"primary_key"`
  77. CreatedAt time.Time `json:"-"`
  78. UpdatedAt time.Time `json:"-"`
  79. UserID string `json:"user_id"`
  80. ClusterID string `json:"cluster_id"`
  81. Type string `json:"admin" gorm:"user"`
  82. }
  83. type NamespaceRole struct {
  84. ID string `json:"id" gorm:"primary_key"`
  85. CreatedAt time.Time `json:"-"`
  86. UpdatedAt time.Time `json:"-"`
  87. UserID string `json:"user_id"`
  88. ClusterID string `json:"cluster_id"`
  89. NamespaceID string `json:"namespace_id"`
  90. Type string `json:"admin" gorm:"user"`
  91. }
  92. type Namespace struct {
  93. ID string `json:"id" gorm:"primary_key"`
  94. CreatedAt time.Time `json:"-"`
  95. UpdatedAt time.Time `json:"-"`
  96. ClusterID string `json:"cluster_id"`
  97. Name string `json:"name"`
  98. }
  99. type Session struct {
  100. ID string `json:"id" gorm:"primary_key"`
  101. CreatedAt time.Time `json:"-"`
  102. Token string `json:"token"`
  103. }
  104. type Token struct {
  105. ID string `json:"id" gorm:"primary_key"`
  106. CreatedAt time.Time `json:"-"`
  107. UpdatedAt time.Time `json:"-"`
  108. ClusterID string `json:"cluster_id"`
  109. UserID string `json:"user_id"`
  110. }
  111. type User struct {
  112. ID string `json:"id" gorm:"primary_key"`
  113. CreatedAt time.Time `json:"-"`
  114. UpdatedAt time.Time `json:"-"`
  115. SSO string `json:"sso"`
  116. FirstName string `json:"first_name"`
  117. LastName string `json:"last_name"`
  118. Email string `json:"email"`
  119. }
  120. type Vpc struct {
  121. ID string `json:"id" gorm:"primary_key"`
  122. CloudID string `json:"cloud_id"`
  123. Name string `json:"name"`
  124. }
  125.  
  126. if !api.Database.HasTable(&Application{}) {
  127. api.Database.CreateTable(&Application{})
  128. }
  129. if !api.Database.HasTable(&Cloud{}) {
  130. api.Database.CreateTable(&Cloud{})
  131. }
  132. if !api.Database.HasTable(&Cluster{}) {
  133. api.Database.CreateTable(&Cluster{})
  134. }
  135. if !api.Database.HasTable(&ClusterRole{}) {
  136. api.Database.CreateTable(&ClusterRole{})
  137. }
  138. if !api.Database.HasTable(&NamespaceRole{}) {
  139. api.Database.CreateTable(&NamespaceRole{})
  140. }
  141. if !api.Database.HasTable(&Namespace{}) {
  142. api.Database.CreateTable(&Namespace{})
  143. }
  144. if !api.Database.HasTable(&Session{}) {
  145. api.Database.CreateTable(&Session{})
  146. }
  147. if !api.Database.HasTable(&Token{}) {
  148. api.Database.CreateTable(&Token{})
  149. }
  150. if !api.Database.HasTable(&User{}) {
  151. api.Database.CreateTable(&User{})
  152. }
  153. if !api.Database.HasTable(&Vpc{}) {
  154. api.Database.CreateTable(&Vpc{})
  155. }
  156. fmt.Println("Tables are created")
  157.  
  158. // Initialize Router
  159. api.Router = mux.NewRouter()
  160.  
  161. api.Router.HandleFunc("/api/v1/applications", api.handleApplications)
  162. api.Router.HandleFunc("/api/v1/application/{id}", api.handleApplication)
  163. api.Router.HandleFunc("/api/v1/applications", api.getApplications).Methods("GET")
  164. api.Router.HandleFunc("/api/v1/application", api.createApplication).Methods("POST")
  165. // api.Router.HandleFunc("/api/v1/application/{id:[0-9]+}", api.getApplication).Methods("GET")
  166. api.Router.HandleFunc("/api/v1/application/{id:[0-9]+}", api.updateApplication).Methods("PUT")
  167. api.Router.HandleFunc("/api/v1/application/{id:[0-9]+}", api.deleteApplication).Methods("DELETE")
  168. }
  169.  
  170. func getApplications(db *gorm.DB, start, count int) ([]API, error) {
  171. return nil, errors.New("Not implemented")
  172. }
  173.  
  174. func (api *API) getApplications(w http.ResponseWriter, r *http.Request) {
  175. count, _ := strconv.Atoi(r.FormValue("count"))
  176. start, _ := strconv.Atoi(r.FormValue("start"))
  177.  
  178. if count > 10 || count < 1 {
  179. count = 10
  180. }
  181. if start < 0 {
  182. start = 0
  183. }
  184.  
  185. applications, err := getApplications(api.Database, start, count)
  186. if err != nil {
  187. respondWithError(w, http.StatusInternalServerError, err.Error())
  188. return
  189. }
  190.  
  191. respondWithJSON(w, http.StatusOK, applications)
  192. }
  193.  
  194. func (api *API) createApplication(w http.ResponseWriter, r *http.Request) {
  195. count, _ := strconv.Atoi(r.FormValue("count"))
  196. start, _ := strconv.Atoi(r.FormValue("start"))
  197.  
  198. type Application struct {
  199. ID string `json:"id" gorm:"primary_key"`
  200. AccessId int64
  201. CreatedAt time.Time `json:"-"`
  202. UpdatedAt time.Time `json:"-"`
  203. Name string `json:"name"`
  204. Ci string `json:"ci"`
  205. }
  206.  
  207. app := Application{}
  208. decoder := json.NewDecoder(r.Body)
  209. if err := decoder.Decode(&app); err != nil {
  210. respondWithError(w, http.StatusBadRequest, "Invalid request payload")
  211. return
  212. }
  213. defer r.Body.Close()
  214. if err := app.createApplication(api.Database); err != nil {
  215. respondWithError(w, http.StatusInternalServerError, err.Error())
  216. return
  217. }
  218. respondWithJSON(w, http.StatusCreated, app)
  219. }
  220.  
  221. func (api *API) getApplication(w http.ResponseWriter, r *http.Request) {
  222.  
  223. type Application struct {
  224. ID string `json:"id" gorm:"primary_key"`
  225. AccessId int64
  226. CreatedAt time.Time `json:"-"`
  227. UpdatedAt time.Time `json:"-"`
  228. Name string `json:"name"`
  229. Ci string `json:"ci"`
  230. }
  231.  
  232. vars := mux.Vars(r)
  233. app := Application{}
  234. id, err := strconv.Atoi(vars["id"])
  235. if err != nil {
  236. respondWithError(w, http.StatusBadRequest, "Invalid Application ID")
  237. return
  238. }
  239.  
  240. if err := app.getApplication(api.Database); err != nil {
  241. switch err {
  242. case sql.ErrNoRows:
  243. respondWithError(w, http.StatusNotFound, "Application not found")
  244. default:
  245. respondWithError(w, http.StatusInternalServerError, err.Error())
  246. }
  247. return
  248. }
  249.  
  250. respondWithJSON(w, http.StatusOK, app)
  251. }
  252.  
  253. func (api *API) updateApplication(w http.ResponseWriter, r *http.Request) {
  254.  
  255. app := models.Application{}
  256. vars := mux.Vars(r)
  257. id, err := strconv.Atoi(vars["id"])
  258. if err != nil {
  259. respondWithError(w, http.StatusBadRequest, "Invalid Application ID")
  260. return
  261. }
  262.  
  263. decoder := json.NewDecoder(r.Body)
  264. if err := decoder.Decode(&app); err != nil {
  265. respondWithError(w, http.StatusBadRequest, "Invalid resquest payload")
  266. return
  267. }
  268. defer r.Body.Close()
  269. app.ID = ""
  270.  
  271. if err := app.updateApplication(api.Database); err != nil {
  272. respondWithError(w, http.StatusInternalServerError, err.Error())
  273. return
  274. }
  275.  
  276. respondWithJSON(w, http.StatusOK, app)
  277. }
  278.  
  279. func (api *API) deleteApplication(w http.ResponseWriter, r *http.Request) {
  280.  
  281. app := models.Application{}
  282. vars := mux.Vars(r)
  283. id, err := strconv.Atoi(vars["id"])
  284. if err != nil {
  285. respondWithError(w, http.StatusBadRequest, "Invalid Application ID")
  286. return
  287. }
  288.  
  289. if err := app.deleteApplication(api.Database); err != nil {
  290. respondWithError(w, http.StatusInternalServerError, err.Error())
  291. return
  292. }
  293.  
  294. respondWithJSON(w, http.StatusOK, map[string]string{"result": "success"})
  295. }
  296.  
  297. func respondWithError(w http.ResponseWriter, code int, message string) {
  298. respondWithJSON(w, code, map[string]string{"error": message})
  299. }
  300.  
  301. func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
  302. response, _ := json.Marshal(payload)
  303.  
  304. w.Header().Set("Content-Type", "application/json")
  305. w.WriteHeader(code)
  306. w.Write(response)
  307. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement