Exemple #1
0
// SetRepo is a middleware function that retrieves
// the repository and stores in the context.
func SetRepo(c *web.C, h http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		var (
			ctx   = context.FromC(*c)
			host  = c.URLParams["host"]
			owner = c.URLParams["owner"]
			name  = c.URLParams["name"]
			user  = ToUser(c)
		)

		repo, err := datastore.GetRepoName(ctx, host, owner, name)
		switch {
		case err != nil && user == nil:
			w.WriteHeader(http.StatusUnauthorized)
			return
		case err != nil && user != nil:
			w.WriteHeader(http.StatusNotFound)
			return
		}
		role, _ := datastore.GetPerm(ctx, user, repo)
		RepoToC(c, repo)
		RoleToC(c, role)
		h.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}
Exemple #2
0
// GetCC accepts a request to retrieve the latest build
// status for the given repository from the datastore and
// in CCTray XML format.
//
//     GET /api/badge/:host/:owner/:name/cc.xml
//
func GetCC(c web.C, w http.ResponseWriter, r *http.Request) {
	var ctx = context.FromC(c)
	var (
		host  = c.URLParams["host"]
		owner = c.URLParams["owner"]
		name  = c.URLParams["name"]
	)

	w.Header().Set("Content-Type", "application/xml")

	repo, err := datastore.GetRepoName(ctx, host, owner, name)
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	commits, err := datastore.GetCommitList(ctx, repo, 1, 0)
	if err != nil || len(commits) == 0 {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	var link = httputil.GetURL(r) + "/" + repo.Host + "/" + repo.Owner + "/" + repo.Name
	var cc = model.NewCC(repo, commits[0], link)
	xml.NewEncoder(w).Encode(cc)
}
Exemple #3
0
// GetBadge accepts a request to retrieve the named
// repo and branhes latest build details from the datastore
// and return an SVG badges representing the build results.
//
//     GET /api/badge/:host/:owner/:name/status.svg
//
func GetBadge(c web.C, w http.ResponseWriter, r *http.Request) {
	var ctx = context.FromC(c)
	var (
		host   = c.URLParams["host"]
		owner  = c.URLParams["owner"]
		name   = c.URLParams["name"]
		branch = r.FormValue("branch")
		style  = r.FormValue("style")
	)

	// an SVG response is always served, even when error, so
	// we can go ahead and set the content type appropriately.
	w.Header().Set("Content-Type", "image/svg+xml")

	badge, ok := badgeStyles[style]
	if !ok {
		badge = defaultBadge
	}

	repo, err := datastore.GetRepoName(ctx, host, owner, name)
	if err != nil {
		w.Write(badge.none)
		return
	}
	if len(branch) == 0 {
		branch = model.DefaultBranch
	}
	commit, _ := datastore.GetCommitLast(ctx, repo, branch)

	// if no commit was found then display
	// the 'none' badge, instead of throwing
	// an error response
	if commit == nil {
		w.Write(badge.none)
		return
	}

	switch commit.Status {
	case model.StatusSuccess:
		w.Write(badge.success)
	case model.StatusFailure:
		w.Write(badge.failure)
	case model.StatusError:
		w.Write(badge.err)
	case model.StatusEnqueue, model.StatusStarted:
		w.Write(badge.started)
	default:
		w.Write(badge.none)
	}
}
Exemple #4
0
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
	}
}
Exemple #5
0
// 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.
//
//     GET /api/hook/:host
//
func PostHook(c web.C, w http.ResponseWriter, r *http.Request) {
	var ctx = context.FromC(c)
	var host = c.URLParams["host"]
	var token = c.URLParams["token"]
	var remote = remote.Lookup(host)
	if remote == nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// parse the hook payload
	hook, err := remote.ParseHook(r)
	if err != nil {
		log.Printf("Unable to parse hook. %s\n", err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// in some cases we have neither a hook nor error. An example
	// would be GitHub sending a ping request to the URL, in which
	// case we'll just exit quiely with an 'OK'
	if hook == nil || strings.Contains(hook.Message, "[CI SKIP]") {
		w.WriteHeader(http.StatusOK)
		return
	}

	// fetch the repository from the database
	repo, err := datastore.GetRepoName(ctx, remote.GetHost(), hook.Owner, hook.Repo)
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// each hook contains a token to verify the sender. If the token
	// is not provided or does not match, exit
	if len(repo.Token) == 0 || repo.Token != token {
		log.Printf("Rejected post commit hook for %s. Token mismatch\n", repo.Name)
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	if repo.Active == false ||
		(repo.PostCommit == false && len(hook.PullRequest) == 0) ||
		(repo.PullRequest == false && len(hook.PullRequest) != 0) {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// fetch the user from the database that owns this repo
	user, err := datastore.GetUser(ctx, repo.UserID)
	if err != 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 {
		log.Printf("Unable to refresh token. %s\n", err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// featch the .drone.yml file from the database
	yml, err := remote.GetScript(user, repo, hook)
	if err != nil {
		log.Printf("Unable to fetch .drone.yml file. %s\n", err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// verify the commit hooks branch matches the list of approved
	// branches (unless it is a pull request). Note that we don't really
	// care if parsing the yaml fails here.
	s, _ := script.ParseBuild(string(yml))
	if len(hook.PullRequest) == 0 && !s.MatchBranch(hook.Branch) {
		w.WriteHeader(http.StatusOK)
		return
	}

	commit := model.Commit{
		RepoID:      repo.ID,
		Status:      model.StatusEnqueue,
		Sha:         hook.Sha,
		Branch:      hook.Branch,
		PullRequest: hook.PullRequest,
		Timestamp:   hook.Timestamp,
		Message:     hook.Message,
		Config:      string(yml),
	}
	commit.SetAuthor(hook.Author)

	// inserts the commit into the database
	if err := datastore.PostCommit(ctx, &commit); err != nil {
		log.Printf("Unable to persist commit %s@%s. %s\n", commit.Sha, commit.Branch, err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	owner, err := datastore.GetUser(ctx, repo.UserID)
	if err != nil {
		log.Printf("Unable to retrieve repository owner. %s.\n", err)
		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)
}
Exemple #6
0
// 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.
//
//     GET /api/hook/:host
//
func PostHook(c web.C, w http.ResponseWriter, r *http.Request) {
	var ctx = context.FromC(c)
	var host = c.URLParams["host"]
	var remote = remote.Lookup(host)
	if remote == nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// parse the hook payload
	hook, err := remote.ParseHook(r)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// in some cases we have neither a hook nor error. An example
	// would be GitHub sending a ping request to the URL, in which
	// case we'll just exit quiely with an 'OK'
	if hook == nil || strings.Contains(hook.Message, "[CI SKIP]") {
		w.WriteHeader(http.StatusOK)
		return
	}

	// fetch the repository from the database
	repo, err := datastore.GetRepoName(ctx, remote.GetHost(), hook.Owner, hook.Repo)
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	if repo.Active == false ||
		(repo.PostCommit == false && len(hook.PullRequest) == 0) ||
		(repo.PullRequest == false && len(hook.PullRequest) != 0) {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// fetch the user from the database that owns this repo
	user, err := datastore.GetUser(ctx, repo.UserID)
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// featch the .drone.yml file from the database
	yml, err := remote.GetScript(user, repo, hook)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// verify the commit hooks branch matches the list of approved
	// branches (unless it is a pull request). Note that we don't really
	// care if parsing the yaml fails here.
	s, _ := script.ParseBuild(string(yml))
	if len(hook.PullRequest) == 0 && !s.MatchBranch(hook.Branch) {
		w.WriteHeader(http.StatusOK)
		return
	}

	commit := model.Commit{
		RepoID:      repo.ID,
		Status:      model.StatusEnqueue,
		Sha:         hook.Sha,
		Branch:      hook.Branch,
		PullRequest: hook.PullRequest,
		Timestamp:   hook.Timestamp,
		Message:     hook.Message,
		Config:      string(yml),
	}
	commit.SetAuthor(hook.Author)

	// inserts the commit into the database
	if err := datastore.PostCommit(ctx, &commit); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	owner, err := datastore.GetUser(ctx, repo.UserID)
	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)
}
Exemple #7
0
// GetLogin accepts a request to authorize the user and to
// return a valid OAuth2 access token. The access token is
// returned as url segment #access_token
//
//     GET /login/:host
//
func GetLogin(c web.C, w http.ResponseWriter, r *http.Request) {
	var ctx = context.FromC(c)
	var host = c.URLParams["host"]
	var redirect = "/"
	var remote = remote.Lookup(host)
	if remote == nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// authenticate the user
	login, err := remote.Authorize(w, r)
	if err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusBadRequest)
		return
	} else if login == nil {
		// in this case we probably just redirected
		// the user, so we can exit with no error
		return
	}

	// get the user from the database
	u, err := datastore.GetUserLogin(ctx, host, login.Login)
	if err != nil {
		// if self-registration is disabled we should
		// return a notAuthorized error. the only exception
		// is if no users exist yet in the system we'll proceed.
		if capability.Enabled(ctx, capability.Registration) == false {
			users, err := datastore.GetUserList(ctx)
			if err != nil || len(users) != 0 {
				log.Println("Unable to create account. Registration is closed")
				w.WriteHeader(http.StatusForbidden)
				return
			}
		}

		// create the user account
		u = model.NewUser(remote.GetKind(), login.Login, login.Email)
		u.Name = login.Name
		u.SetEmail(login.Email)

		// insert the user into the database
		if err := datastore.PostUser(ctx, u); err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusBadRequest)
			return
		}

		// if this is the first user, they
		// should be an admin.
		if u.ID == 1 {
			u.Admin = true
		}
	}

	// update the user access token
	// in case it changed in GitHub
	u.Access = login.Access
	u.Secret = login.Secret
	u.Name = login.Name
	u.SetEmail(login.Email)
	u.Syncing = true //u.IsStale() // todo (badrydzewski) should not always sync
	if err := datastore.PutUser(ctx, u); err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// look at the last synchronized date to determine if
	// we need to re-sync the account.
	//
	// todo(bradrydzewski) this should move to a server/sync package and
	//      should be injected into this struct, just like the database code.
	//
	// todo(bradrydzewski) this login should be a bit more intelligent
	//      than the current implementation.
	if u.Syncing {
		redirect = "/sync"
		log.Println("sync user account.", u.Login)

		// sync inside a goroutine. This should eventually be moved to
		// its own package / sync utility.
		go func() {
			repos, err := remote.GetRepos(u)
			if err != nil {
				log.Println("Error syncing user account, listing repositories", u.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.", u.Login, repo.Name, err)
						continue
					}
				}

				// add user permissions
				perm := model.Perm{
					UserID: u.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.", u.Login, repo.Name, err)
					continue
				}

				log.Println("Successfully syced repo.", u.Login+"/"+repo.Name)
			}

			u.Synced = time.Now().UTC().Unix()
			u.Syncing = false
			if err := datastore.PutUser(ctx, u); err != nil {
				log.Println("Error syncing user account, updating sync date", u.Login, err)
				return
			}
		}()
	}

	token, err := session.GenerateToken(ctx, r, u)
	if err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	redirect = redirect + "#access_token=" + token

	http.Redirect(w, r, redirect, http.StatusSeeOther)
}