// PutUser accepts a request to update the currently // authenticated User profile. // // PUT /api/user // func PutUser(c web.C, w http.ResponseWriter, r *http.Request) { var ctx = context.FromC(c) var user = ToUser(c) if user == nil { w.WriteHeader(http.StatusUnauthorized) return } // unmarshal the repository from the payload defer r.Body.Close() in := model.User{} if err := json.NewDecoder(r.Body).Decode(&in); err != nil { w.WriteHeader(http.StatusBadRequest) return } // update the user email if len(in.Email) != 0 { user.SetEmail(in.Email) } // update the user full name if len(in.Name) != 0 { user.Name = in.Name } // update the database if err := datastore.PutUser(ctx, user); err != nil { w.WriteHeader(http.StatusInternalServerError) return } json.NewEncoder(w).Encode(user) }
// PostHook accepts a post-commit hook and parses the payload // in order to trigger a build. The payload is specified to the // remote system (ie GitHub) and will therefore get parsed by // the appropriate remote plugin. // // POST /api/repos/{host}/{owner}/{name}/branches/{branch}/commits/{commit} // func PostCommit(c web.C, w http.ResponseWriter, r *http.Request) { var ctx = context.FromC(c) var ( branch = c.URLParams["branch"] hash = c.URLParams["commit"] host = c.URLParams["host"] repo = ToRepo(c) remote = remote.Lookup(host) ) commit, err := datastore.GetCommitSha(ctx, repo, branch, hash) if err != nil { w.WriteHeader(http.StatusNotFound) return } if commit.Status == model.StatusStarted || commit.Status == model.StatusEnqueue { w.WriteHeader(http.StatusConflict) return } commit.Status = model.StatusEnqueue commit.Started = 0 commit.Finished = 0 commit.Duration = 0 if err := datastore.PutCommit(ctx, commit); err != nil { w.WriteHeader(http.StatusInternalServerError) return } owner, err := datastore.GetUser(ctx, repo.UserID) if err != nil { w.WriteHeader(http.StatusBadRequest) return } // Request a new token and update user_token, err := remote.GetToken(owner) if user_token != nil { owner.Access = user_token.AccessToken owner.Secret = user_token.RefreshToken owner.TokenExpiry = user_token.Expiry datastore.PutUser(ctx, owner) } else if err != nil { w.WriteHeader(http.StatusBadRequest) return } // drop the items on the queue go worker.Do(ctx, &worker.Work{ User: owner, Repo: repo, Commit: commit, Host: httputil.GetURL(r), }) w.WriteHeader(http.StatusOK) }
func SyncUser(ctx context.Context, user *model.User, remote remote.Remote) { repos, err := remote.GetRepos(user) if err != nil { log.Println("Error syncing user account, listing repositories", user.Login, err) return } // insert all repositories for _, repo := range repos { var role = repo.Role if err := datastore.PostRepo(ctx, repo); err != nil { // typically we see a failure because the repository already exists // in which case, we can retrieve the existing record to get the ID. repo, err = datastore.GetRepoName(ctx, repo.Host, repo.Owner, repo.Name) if err != nil { log.Println("Error adding repo.", user.Login, repo.Name, err) continue } } // add user permissions perm := model.Perm{ UserID: user.ID, RepoID: repo.ID, Read: role.Read, Write: role.Write, Admin: role.Admin, } if err := datastore.PostPerm(ctx, &perm); err != nil { log.Println("Error adding permissions.", user.Login, repo.Name, err) continue } log.Printf("Successfully synced repo. %s/%s\n", repo.Owner, repo.Name) } user.Synced = time.Now().UTC().Unix() user.Syncing = false if err := datastore.PutUser(ctx, user); err != nil { log.Println("Error syncing user account, updating sync date", user.Login, err) return } }
// PostUserSync accepts a request to post user sync // // POST /api/user/sync // func PostUserSync(c web.C, w http.ResponseWriter, r *http.Request) { var ctx = context.FromC(c) var user = ToUser(c) if user == nil { w.WriteHeader(http.StatusUnauthorized) return } var remote = remote.Lookup(user.Remote) if remote == nil { w.WriteHeader(http.StatusNotFound) return } if user.Syncing { w.WriteHeader(http.StatusConflict) return } // Request a new token and update user_token, err := remote.GetToken(user) if user_token != nil { user.Access = user_token.AccessToken user.Secret = user_token.RefreshToken user.TokenExpiry = user_token.Expiry } else if err != nil { w.WriteHeader(http.StatusNotFound) return } user.Syncing = true if err := datastore.PutUser(ctx, user); err != nil { w.WriteHeader(http.StatusNotFound) return } go sync.SyncUser(ctx, user, remote) w.WriteHeader(http.StatusNoContent) return }
// DelRepo accepts a request to delete the named // repository. // // DEL /api/repos/:host/:owner/:name // func DelRepo(c web.C, w http.ResponseWriter, r *http.Request) { var ctx = context.FromC(c) var repo = ToRepo(c) // completely remove the repository from the database var user = ToUser(c) var remote = remote.Lookup(repo.Host) if remote == nil { log.Printf("[ERROR] no remote for host '%s' found", repo.Host) } else { // Request a new token and update user_token, err := remote.GetToken(user) if err != nil { log.Printf("[ERROR] no token for user '%s' on remote '%s' ", user.Email, repo.Host) } else { if user_token != nil { user.Access = user_token.AccessToken user.Secret = user_token.RefreshToken user.TokenExpiry = user_token.Expiry datastore.PutUser(ctx, user) } // setup the post-commit hook with the remote system and // and deactiveate this hook/user on the remote system var hook = fmt.Sprintf("%s/api/hook/%s/%s", httputil.GetURL(r), repo.Remote, repo.Token) if err := remote.Deactivate(user, repo, hook); err != nil { log.Printf("[ERROR] deactivate on remote '%s' failed: %s", repo.Host, err) } } } // fail through: if any of the actions on the remote failed // we try to delete the repo in our datastore anyway if err := datastore.DelRepo(ctx, repo); err != nil { w.WriteHeader(http.StatusInternalServerError) } else { w.WriteHeader(http.StatusNoContent) } }
// PostRepo accapets a request to activate the named repository // in the datastore. It returns a 201 status created if successful // // POST /api/repos/:host/:owner/:name // func PostRepo(c web.C, w http.ResponseWriter, r *http.Request) { var ctx = context.FromC(c) var repo = ToRepo(c) var user = ToUser(c) // update the repo active flag and fields repo.Active = true repo.PullRequest = true repo.PostCommit = true repo.UserID = user.ID repo.Timeout = 3600 // default to 1 hour // generate a secret key for post-commit hooks if len(repo.Token) == 0 { repo.Token = model.GenerateToken() } // generates the rsa key if len(repo.PublicKey) == 0 || len(repo.PrivateKey) == 0 { key, err := sshutil.GeneratePrivateKey() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } repo.PublicKey = sshutil.MarshalPublicKey(&key.PublicKey) repo.PrivateKey = sshutil.MarshalPrivateKey(key) } var remote = remote.Lookup(repo.Host) if remote == nil { w.WriteHeader(http.StatusNotFound) return } // Request a new token and update user_token, err := remote.GetToken(user) if user_token != nil { user.Access = user_token.AccessToken user.Secret = user_token.RefreshToken user.TokenExpiry = user_token.Expiry datastore.PutUser(ctx, user) } else if err != nil { w.WriteHeader(http.StatusBadRequest) return } // setup the post-commit hook with the remote system and // if necessary, register the public key var hook = fmt.Sprintf("%s/api/hook/%s/%s", httputil.GetURL(r), repo.Remote, repo.Token) if err := remote.Activate(user, repo, hook); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if err := datastore.PutRepo(ctx, repo); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(repo) }