func AdminUserUpdate(w http.ResponseWriter, r *http.Request, u *User) error { // get the ID from the URL parameter idstr := r.FormValue("id") id, err := strconv.Atoi(idstr) if err != nil { return err } // get the user from the database user, err := database.GetUser(int64(id)) if err != nil { return err } // update if user is administrator or not switch r.FormValue("Admin") { case "true": user.Admin = true case "false": user.Admin = false } // saving user if err := database.SaveUser(user); err != nil { return err } return RenderText(w, http.StatusText(http.StatusOK), http.StatusOK) }
func RegisterPost(w http.ResponseWriter, r *http.Request) error { // verify the token and extract the username token := r.FormValue("token") email := authcookie.Login(token, secret) if len(email) == 0 { return RenderTemplate(w, "register.html", &struct{ Error string }{"Your registration email is expired."}) } // set the email and name user := NewUser(r.FormValue("name"), email) // set the new password password := r.FormValue("password") if err := user.SetPassword(password); err != nil { return RenderTemplate(w, "register.html", &struct{ Error string }{err.Error()}) } // verify fields are correct if err := user.Validate(); err != nil { return RenderTemplate(w, "register.html", &struct{ Error string }{err.Error()}) } // save to the database if err := database.SaveUser(user); err != nil { return err } // add the user to the session object SetCookie(w, r, "_sess", user.Email) // redirect the user to their dashboard http.Redirect(w, r, "/dashboard", http.StatusSeeOther) return nil }
// TestUpdateUser tests the ability to updatee an // existing User in the database. func TestUpdateUser(t *testing.T) { Setup() defer Teardown() // get the user we plan to update user, err := database.GetUser(1) if err != nil { t.Error(err) } // update fields user.Email = "*****@*****.**" user.Password = "******" // update the database if err := database.SaveUser(user); err != nil { t.Error(err) } // get the updated user updatedUser, err := database.GetUser(1) if err != nil { t.Error(err) } // verify the updated fields if user.Email != updatedUser.Email { t.Errorf("Exepected Email %s, got %s", user.Email, updatedUser.Email) } if user.Password != updatedUser.Password { t.Errorf("Exepected Password %s, got %s", user.Email, updatedUser.Password) } }
func ResetPost(w http.ResponseWriter, r *http.Request) error { // verify the token and extract the username token := r.FormValue("token") email, err := passwordreset.VerifyToken(token, database.GetPassEmail, secret) if err != nil { return RenderTemplate(w, "reset.html", &struct{ Error string }{"Your password reset request is expired."}) } // get the user from the database user, err := database.GetUserEmail(email) if err != nil { return RenderTemplate(w, "reset.html", &struct{ Error string }{"Unable to locate user account."}) } // get the new password password := r.FormValue("password") if err := user.SetPassword(password); err != nil { return RenderTemplate(w, "reset.html", &struct{ Error string }{err.Error()}) } // save to the database if err := database.SaveUser(user); err != nil { return RenderTemplate(w, "reset.html", &struct{ Error string }{"Unable to update password. Please try again"}) } // add the user to the session object SetCookie(w, r, "_sess", user.Email) http.Redirect(w, r, "/dashboard", http.StatusSeeOther) return nil }
// update a specific user's password func UserPassUpdate(w http.ResponseWriter, r *http.Request, u *User) error { // set the name and email from the form data pass := r.FormValue("password") if err := u.SetPassword(pass); err != nil { return RenderError(w, err, http.StatusBadRequest) } // save the updated password to the database if err := database.SaveUser(u); err != nil { return RenderError(w, err, http.StatusBadRequest) } return RenderText(w, http.StatusText(http.StatusOK), http.StatusOK) }
func LinkGithub(w http.ResponseWriter, r *http.Request, u *User) error { // get settings from database settings := database.SettingsMust() // github OAuth2 Data var oauth = oauth2.Client{ RedirectURL: settings.URL().String() + "/auth/login/github", AccessTokenURL: "https://" + settings.GitHubDomain + "/login/oauth/access_token", AuthorizationURL: "https://" + settings.GitHubDomain + "/login/oauth/authorize", ClientId: settings.GitHubKey, ClientSecret: settings.GitHubSecret, } // get the OAuth code code := r.FormValue("code") if len(code) == 0 { scope := "repo,repo:status,user:email" state := "FqB4EbagQ2o" redirect := oauth.AuthorizeRedirect(scope, state) http.Redirect(w, r, redirect, http.StatusSeeOther) return nil } // exchange code for an auth token token, err := oauth.GrantToken(code) if err != nil { log.Println("Error granting GitHub authorization token") return err } // create the client client := github.New(token.AccessToken) client.ApiUrl = settings.GitHubApiUrl // get the user information githubUser, err := client.Users.Current() if err != nil { log.Println("Error retrieving currently authenticated GitHub user") return err } // save the github token to the user account u.GithubToken = token.AccessToken u.GithubLogin = githubUser.Login if err := database.SaveUser(u); err != nil { log.Println("Error persisting user's GitHub auth token to the database") return err } http.Redirect(w, r, "/new/github.com", http.StatusSeeOther) return nil }
// update a specific user func UserUpdate(w http.ResponseWriter, r *http.Request, u *User) error { // set the name and email from the form data u.Name = r.FormValue("name") u.SetEmail(r.FormValue("email")) if err := u.Validate(); err != nil { return RenderError(w, err, http.StatusBadRequest) } if err := database.SaveUser(u); err != nil { return RenderError(w, err, http.StatusBadRequest) } return RenderText(w, http.StatusText(http.StatusOK), http.StatusOK) }
func InstallPost(w http.ResponseWriter, r *http.Request) error { // we can only perform the inital installation if no // users exist in the system if users, err := database.ListUsers(); err != nil { return RenderError(w, err, http.StatusBadRequest) } else if len(users) != 0 { // if users exist in the systsem // we should render a NotFound page return RenderNotFound(w) } // set the email and name user := NewUser(r.FormValue("name"), r.FormValue("email")) user.Admin = true // set the new password if err := user.SetPassword(r.FormValue("password")); err != nil { return RenderError(w, err, http.StatusBadRequest) } // verify fields are correct if err := user.Validate(); err != nil { return RenderError(w, err, http.StatusBadRequest) } // save to the database if err := database.SaveUser(user); err != nil { return RenderError(w, err, http.StatusBadRequest) } // update settings settings := Settings{} settings.Domain = r.FormValue("Domain") settings.Scheme = r.FormValue("Scheme") settings.GitHubApiUrl = "https://api.github.com" settings.GitHubDomain = "github.com" settings.GitlabApiUrl = "https://gitlab.com" settings.GitlabDomain = "gitlab.com" database.SaveSettings(&settings) // add the user to the session object // so that he/she is loggedin SetCookie(w, r, "_sess", user.Email) // send the user to the settings page // to complete the configuration. http.Redirect(w, r, "/account/admin/settings", http.StatusSeeOther) return nil }
func (g *GitlabHandler) Link(w http.ResponseWriter, r *http.Request, u *User) error { token := strings.TrimSpace(r.FormValue("token")) if len(u.GitlabToken) == 0 || token != u.GitlabToken && len(token) > 0 { u.GitlabToken = token settings := database.SettingsMust() gl := gogitlab.NewGitlab(settings.GitlabApiUrl, g.apiPath, u.GitlabToken) _, err := gl.CurrentUser() if err != nil { return fmt.Errorf("Private Token is not valid: %q", err) } if err := database.SaveUser(u); err != nil { return RenderError(w, err, http.StatusBadRequest) } } http.Redirect(w, r, "/new/gitlab", http.StatusSeeOther) return nil }
func Setup() { // create an in-memory database database.Init("sqlite3", ":memory:") // create dummy user data user1 := User{ Password: "******", Name: "Brad Rydzewski", Email: "*****@*****.**", Gravatar: "8c58a0be77ee441bb8f8595b7f1b4e87", Token: "123", Admin: true} user2 := User{ Password: "******", Name: "Thomas Burke", Email: "*****@*****.**", Gravatar: "c62f7126273f7fa786274274a5dec8ce", Token: "456", Admin: false} user3 := User{ Password: "******", Name: "Carlos Morales", Email: "*****@*****.**", Gravatar: "c2180a539620d90d68eaeb848364f1c2", Token: "789", Admin: false} database.SaveUser(&user1) database.SaveUser(&user2) database.SaveUser(&user3) // create dummy team data team1 := Team{ Slug: "drone", Name: "Drone", Email: "*****@*****.**", Gravatar: "8c58a0be77ee441bb8f8595b7f1b4e87"} team2 := Team{ Slug: "github", Name: "Github", Email: "*****@*****.**", Gravatar: "61024896f291303615bcd4f7a0dcfb74"} team3 := Team{ Slug: "golang", Name: "Golang", Email: "*****@*****.**", Gravatar: "991695cc770c6b8354b68cd18c280b95"} database.SaveTeam(&team1) database.SaveTeam(&team2) database.SaveTeam(&team3) // create team membership data database.SaveMember(user1.ID, team1.ID, RoleOwner) database.SaveMember(user2.ID, team1.ID, RoleAdmin) database.SaveMember(user3.ID, team1.ID, RoleWrite) database.SaveMember(user1.ID, team2.ID, RoleOwner) database.SaveMember(user2.ID, team2.ID, RoleAdmin) database.SaveMember(user3.ID, team2.ID, RoleWrite) database.SaveMember(user1.ID, team3.ID, RoleRead) // create dummy repo data repo1 := Repo{ Slug: "github.com/drone/drone", Host: "github.com", Owner: "drone", Name: "drone", Private: true, Disabled: false, SCM: "git", URL: "[email protected]:drone/drone.git", Username: "******", Password: "******", PublicKey: "public key", PrivateKey: "private key", UserID: user1.ID, TeamID: team1.ID, } repo2 := Repo{ Slug: "bitbucket.org/drone/test", Host: "bitbucket.org", Owner: "drone", Name: "test", Private: false, Disabled: false, SCM: "hg", URL: "https://bitbucket.org/drone/test", Username: "******", Password: "******", PublicKey: "public key", PrivateKey: "private key", UserID: user1.ID, TeamID: team1.ID, } repo3 := Repo{ Slug: "bitbucket.org/brydzewski/test", Host: "bitbucket.org", Owner: "brydzewski", Name: "test", Private: false, Disabled: false, SCM: "hg", URL: "https://bitbucket.org/brydzewski/test", Username: "******", Password: "******", PublicKey: "public key", PrivateKey: "private key", UserID: user2.ID, } database.SaveRepo(&repo1) database.SaveRepo(&repo2) database.SaveRepo(&repo3) commit1 := Commit{ RepoID: repo1.ID, Status: "Success", Hash: "4f4c4594be6d6ddbc1c0dd521334f7ecba92b608", Branch: "master", Author: user1.Email, Gravatar: user1.Gravatar, Message: "commit message", } commit2 := Commit{ RepoID: repo1.ID, Status: "Failure", Hash: "0eb2fa13e9f4139e803b6ad37831708d4786c74a", Branch: "master", Author: user1.Email, Gravatar: user1.Gravatar, Message: "commit message", } commit3 := Commit{ RepoID: repo1.ID, Status: "Failure", Hash: "60a7fe87ccf01d0152e53242528399e05acaf047", Branch: "dev", Author: user1.Email, Gravatar: user1.Gravatar, Message: "commit message", } commit4 := Commit{ RepoID: repo2.ID, Status: "Success", Hash: "a4078d1e9a0842cdd214adbf0512578799a4f2ba", Branch: "master", Author: user1.Email, Gravatar: user1.Gravatar, Message: "commit message", } // create dummy commit data database.SaveCommit(&commit1) database.SaveCommit(&commit2) database.SaveCommit(&commit3) database.SaveCommit(&commit4) // create dummy build data database.SaveBuild(&Build{CommitID: commit1.ID, Slug: "node_0.10", Status: "Success", Duration: 60}) database.SaveBuild(&Build{CommitID: commit1.ID, Slug: "node_0.09", Status: "Success", Duration: 70}) database.SaveBuild(&Build{CommitID: commit2.ID, Slug: "node_0.10", Status: "Success", Duration: 10}) database.SaveBuild(&Build{CommitID: commit2.ID, Slug: "node_0.09", Status: "Failure", Duration: 65}) database.SaveBuild(&Build{CommitID: commit3.ID, Slug: "node_0.10", Status: "Failure", Duration: 50}) database.SaveBuild(&Build{CommitID: commit3.ID, Slug: "node_0.09", Status: "Failure", Duration: 55}) }
func RepoCreateGithubLimited(w http.ResponseWriter, r *http.Request, u *User) error { teamName := r.FormValue("team") owner := r.FormValue("owner") name := r.FormValue("name") readToken := r.FormValue("read-token") writeToken := r.FormValue("write-token") u.GithubToken = readToken u.GithubWriteToken = writeToken // get the github settings from the database settings := database.SettingsMust() fmt.Printf("got settings: %s\n", settings) // create the GitHub client rClient := github.New(readToken) wClient := github.New(writeToken) rClient.ApiUrl = settings.GitHubApiUrl wClient.ApiUrl = settings.GitHubApiUrl githubRepo, err := rClient.Repos.Find(owner, name) if err != nil { fmt.Printf("err1, %s\n", err) return err } repo, err := NewGitHubRepo(settings.GitHubDomain, owner, name, githubRepo.Private) if err != nil { fmt.Printf("err2, %s\n", err) return err } repo.URL = fmt.Sprintf("https://%s@%s/%s/%s", readToken, settings.GitHubDomain, owner, name) repo.UserID = u.ID repo.Private = githubRepo.Private // if the user chose to assign to a team account // we need to retrieve the team, verify the user // has access, and then set the team id. if len(teamName) > 0 { team, err := database.GetTeamSlug(teamName) if err != nil { return fmt.Errorf("Unable to find Team %s.", teamName) } // user must be an admin member of the team if ok, _ := database.IsMemberAdmin(u.ID, team.ID); !ok { return fmt.Errorf("Invalid permission to access Team %s.", teamName) } repo.TeamID = team.ID } // create a hook so that we get notified when code // is pushed to the repository and can execute a build. link := fmt.Sprintf("%s://%s/hook/github.com?id=%s", settings.Scheme, settings.Domain, repo.Slug) // add the hook if _, err := wClient.Hooks.CreateUpdate(owner, name, link); err != nil { return fmt.Errorf("Unable to add Hook to your GitHub repository. %s", err.Error()) } // Save to the database if err := database.SaveRepo(repo); err != nil { return fmt.Errorf("Error saving repository to the database. %s", err) } // Save user to the database if err := database.SaveUser(u); err != nil { return fmt.Errorf("Error saving user to the database. %s", err) } return RenderText(w, http.StatusText(http.StatusOK), http.StatusOK) }
func LinkBitbucket(w http.ResponseWriter, r *http.Request, u *User) error { // get settings from database settings := database.SettingsMust() // bitbucket oauth1 consumer var consumer = oauth1.Consumer{ RequestTokenURL: "https://bitbucket.org/api/1.0/oauth/request_token/", AuthorizationURL: "https://bitbucket.org/!api/1.0/oauth/authenticate", AccessTokenURL: "https://bitbucket.org/api/1.0/oauth/access_token/", CallbackURL: settings.URL().String() + "/auth/login/bitbucket", ConsumerKey: settings.BitbucketKey, ConsumerSecret: settings.BitbucketSecret, } // get the oauth verifier verifier := r.FormValue("oauth_verifier") if len(verifier) == 0 { // Generate a Request Token requestToken, err := consumer.RequestToken() if err != nil { return err } // add the request token as a signed cookie SetCookie(w, r, "bitbucket_token", requestToken.Encode()) url, _ := consumer.AuthorizeRedirect(requestToken) http.Redirect(w, r, url, http.StatusSeeOther) return nil } // remove bitbucket token data once before redirecting // back to the application. defer DelCookie(w, r, "bitbucket_token") // get the tokens from the request requestTokenStr := GetCookie(r, "bitbucket_token") requestToken, err := oauth1.ParseRequestTokenStr(requestTokenStr) if err != nil { return err } // exchange for an access token accessToken, err := consumer.AuthorizeToken(requestToken, verifier) if err != nil { return err } // create the Bitbucket client client := bitbucket.New( settings.BitbucketKey, settings.BitbucketSecret, accessToken.Token(), accessToken.Secret(), ) // get the currently authenticated Bitbucket User user, err := client.Users.Current() if err != nil { return err } // update the user account u.BitbucketLogin = user.User.Username u.BitbucketToken = accessToken.Token() u.BitbucketSecret = accessToken.Secret() if err := database.SaveUser(u); err != nil { return err } http.Redirect(w, r, "/new/bitbucket.org", http.StatusSeeOther) return nil }