merged from upstream/master

This commit is contained in:
wknet123 2016-02-24 20:13:54 +08:00
commit 386de12444
16 changed files with 285 additions and 167 deletions

View File

@ -40,7 +40,7 @@ func (b *BaseAPI) DecodeJsonReq(v interface{}) {
err := json.Unmarshal(b.Ctx.Input.CopyBody(1<<32), v)
if err != nil {
beego.Error("Error while decoding the json request:", err)
b.CustomAbort(400, "Invalid json request")
b.CustomAbort(http.StatusBadRequest, "Invalid json request")
}
}
@ -49,17 +49,17 @@ func (b *BaseAPI) ValidateUser() int {
sessionUserId := b.GetSession("userId")
if sessionUserId == nil {
beego.Warning("No user id in session, canceling request")
b.CustomAbort(401, "")
b.CustomAbort(http.StatusUnauthorized, "")
}
userId := sessionUserId.(int)
u, err := dao.GetUser(models.User{UserId: userId})
if err != nil {
beego.Error("Error occurred in GetUser:", err)
b.CustomAbort(500, "Internal error.")
b.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if u == nil {
beego.Warning("User was deleted already, user id: ", userId, " canceling request.")
b.CustomAbort(401, "")
b.CustomAbort(http.StatusUnauthorized, "")
}
return userId
}

View File

@ -17,6 +17,7 @@ package api
import (
"fmt"
"log"
"net/http"
"github.com/vmware/harbor/dao"
"github.com/vmware/harbor/models"
@ -48,15 +49,15 @@ func (p *ProjectAPI) Prepare() {
p.projectId, err = strconv.ParseInt(id_str, 10, 64)
if err != nil {
log.Printf("Error parsing project id: %s, error: %v", id_str, err)
p.CustomAbort(400, "invalid project id")
p.CustomAbort(http.StatusBadRequest, "invalid project id")
}
exist, err := dao.ProjectExists(p.projectId)
if err != nil {
log.Printf("Error occurred in ProjectExists: %v", err)
p.CustomAbort(500, "Internal error.")
p.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if !exist {
p.CustomAbort(404, fmt.Sprintf("project does not exist, id: %v", p.projectId))
p.CustomAbort(http.StatusNotFound, fmt.Sprintf("project does not exist, id: %v", p.projectId))
}
}
}
@ -71,7 +72,7 @@ func (p *ProjectAPI) Post() {
err := validateProjectReq(req)
if err != nil {
beego.Error("Invalid project request, error: ", err)
p.RenderError(400, "Invalid request for creating project")
p.RenderError(http.StatusBadRequest, "Invalid request for creating project")
return
}
projectName := req.ProjectName
@ -80,14 +81,14 @@ func (p *ProjectAPI) Post() {
beego.Error("Error happened checking project existence in db:", err, ", project name:", projectName)
}
if exist {
p.RenderError(409, "")
p.RenderError(http.StatusConflict, "")
return
}
project := models.Project{OwnerId: p.userId, Name: projectName, CreationTime: time.Now(), Public: public}
err = dao.AddProject(project)
if err != nil {
beego.Error("Failed to add project, error: %v", err)
p.RenderError(500, "Failed to add project")
p.RenderError(http.StatusInternalServerError, "Failed to add project")
}
}
@ -96,11 +97,11 @@ func (p *ProjectAPI) Head() {
result, err := dao.ProjectExists(projectName)
if err != nil {
beego.Error("Error while communicating with DB: ", err)
p.RenderError(500, "Error while communicating with DB")
p.RenderError(http.StatusInternalServerError, "Error while communicating with DB")
return
}
if !result {
p.RenderError(404, "")
p.RenderError(http.StatusNotFound, "")
return
}
}
@ -117,7 +118,7 @@ func (p *ProjectAPI) Get() {
projectList, err := dao.QueryProject(queryProject)
if err != nil {
beego.Error("Error occurred in QueryProject:", err)
p.CustomAbort(500, "Internal error.")
p.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
for i := 0; i < len(projectList); i++ {
if isProjectAdmin(p.userId, projectList[i].ProjectId) {
@ -135,7 +136,7 @@ func (p *ProjectAPI) Put() {
projectId, err := strconv.ParseInt(p.Ctx.Input.Param(":id"), 10, 64)
if err != nil {
beego.Error("Error parsing project id:", projectId, ", error: ", err)
p.RenderError(400, "invalid project id")
p.RenderError(http.StatusBadRequest, "invalid project id")
return
}
@ -145,13 +146,13 @@ func (p *ProjectAPI) Put() {
}
if !isProjectAdmin(p.userId, projectId) {
beego.Warning("Current user, id:", p.userId, ", does not have project admin role for project, id:", projectId)
p.RenderError(403, "")
p.RenderError(http.StatusForbidden, "")
return
}
err = dao.ToggleProjectPublicity(p.projectId, public)
if err != nil {
beego.Error("Error while updating project, project id:", projectId, ", error:", err)
p.RenderError(500, "Failed to update project")
p.RenderError(http.StatusInternalServerError, "Failed to update project")
}
}
@ -173,7 +174,7 @@ func (p *ProjectAPI) FilterAccessLog() {
accessLogList, err := dao.GetAccessLogs(query)
if err != nil {
log.Printf("Error occurred in GetAccessLogs: %v", err)
p.CustomAbort(500, "Internal error.")
p.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
p.Data["json"] = accessLogList
p.ServeJSON()

View File

@ -15,12 +15,13 @@
package api
import (
"net/http"
"strconv"
"github.com/vmware/harbor/dao"
"github.com/vmware/harbor/models"
"github.com/astaxie/beego"
"strconv"
)
type ProjectMemberAPI struct {
@ -40,18 +41,18 @@ func (pma *ProjectMemberAPI) Prepare() {
pid, err := strconv.ParseInt(pma.Ctx.Input.Param(":pid"), 10, 64)
if err != nil {
beego.Error("Error parsing project id:", pid, ", error:", err)
pma.CustomAbort(400, "invalid project Id")
pma.CustomAbort(http.StatusBadRequest, "invalid project Id")
return
}
p, err := dao.GetProjectById(models.Project{ProjectId: pid})
p, err := dao.GetProjectById(pid)
if err != nil {
beego.Error("Error occurred in GetProjectById:", err)
pma.CustomAbort(500, "Internal error.")
pma.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if p == nil {
beego.Warning("Project with id:", pid, "does not exist.")
pma.CustomAbort(404, "Project does not exist")
pma.CustomAbort(http.StatusNotFound, "Project does not exist")
}
pma.project = p
pma.currentUserId = pma.ValidateUser()
@ -64,7 +65,7 @@ func (pma *ProjectMemberAPI) Prepare() {
memberId, err := strconv.Atoi(mid)
if err != nil {
beego.Error("Invalid member Id, error:", err)
pma.CustomAbort(400, "Invalid member id")
pma.CustomAbort(http.StatusBadRequest, "Invalid member id")
}
pma.memberId = memberId
}
@ -74,17 +75,16 @@ func (pma *ProjectMemberAPI) Get() {
pid := pma.project.ProjectId
if !CheckProjectPermission(pma.currentUserId, pid) {
beego.Warning("Current user, user id :", pma.currentUserId, "does not have permission for project, id:", pid)
pma.RenderError(403, "")
pma.RenderError(http.StatusForbidden, "")
return
}
if pma.memberId == 0 { //member id not set return list of the members
queryProject := models.Project{ProjectId: pid}
username := pma.GetString("username")
queryUser := models.User{Username: "%" + username + "%"}
userList, err := dao.GetUserByProject(queryProject, queryUser)
userList, err := dao.GetUserByProject(pid, queryUser)
if err != nil {
beego.Error("Failed to query database for member list, error:", err)
pma.RenderError(500, "Internal Server Error")
pma.RenderError(http.StatusInternalServerError, "Internal Server Error")
return
}
pma.Data["json"] = userList
@ -92,14 +92,14 @@ func (pma *ProjectMemberAPI) Get() {
roleList, err := dao.GetUserProjectRoles(models.User{UserId: pma.memberId}, pid)
if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err)
pma.CustomAbort(500, "Internal error.")
pma.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
//return empty role list to indicate if a user is not a member
result := make(map[string]interface{})
user, err := dao.GetUser(models.User{UserId: pma.memberId})
if err != nil {
beego.Error("Error occurred in GetUser:", err)
pma.CustomAbort(500, "Internal error.")
pma.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
result["user_name"] = user.Username
result["user_id"] = pma.memberId
@ -115,11 +115,11 @@ func (pma *ProjectMemberAPI) Post() {
rolelist, err := dao.GetUserProjectRoles(userQuery, pid)
if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err)
pma.CustomAbort(500, "Internal error.")
pma.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if len(rolelist) == 0 {
beego.Warning("Current user, id:", pma.currentUserId, "does not have project admin role for project, id:", pid)
pma.RenderError(403, "")
pma.RenderError(http.StatusForbidden, "")
return
}
var req memberReq
@ -128,17 +128,17 @@ func (pma *ProjectMemberAPI) Post() {
userId := CheckUserExists(username)
if userId <= 0 {
beego.Warning("User does not exist, user name:", username)
pma.RenderError(404, "User does not exist")
pma.RenderError(http.StatusNotFound, "User does not exist")
return
}
rolelist, err = dao.GetUserProjectRoles(models.User{UserId: userId}, pid)
if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err)
pma.CustomAbort(500, "Internal error.")
pma.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if len(rolelist) > 0 {
beego.Warning("user is already added to project, user id:", userId, ", project id:", pid)
pma.RenderError(409, "user is ready in project")
pma.RenderError(http.StatusConflict, "user is ready in project")
return
}
@ -146,7 +146,7 @@ func (pma *ProjectMemberAPI) Post() {
err = dao.AddUserProjectRole(userId, pid, int(rid))
if err != nil {
beego.Error("Failed to update DB to add project user role, project id:", pid, ", user id:", userId, ", role id:", rid)
pma.RenderError(500, "Failed to update data in database")
pma.RenderError(http.StatusInternalServerError, "Failed to update data in database")
return
}
}
@ -159,11 +159,11 @@ func (pma *ProjectMemberAPI) Put() {
rolelist, err := dao.GetUserProjectRoles(userQuery, pid)
if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err)
pma.CustomAbort(500, "Internal error.")
pma.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if len(rolelist) == 0 {
beego.Warning("Current user, id:", pma.currentUserId, ", does not have project admin role for project, id:", pid)
pma.RenderError(403, "")
pma.RenderError(http.StatusForbidden, "")
return
}
var req memberReq
@ -171,7 +171,7 @@ func (pma *ProjectMemberAPI) Put() {
roleList, err := dao.GetUserProjectRoles(models.User{UserId: mid}, pid)
if len(roleList) == 0 {
beego.Warning("User is not in project, user id:", mid, ", project id:", pid)
pma.RenderError(404, "user not exist in project")
pma.RenderError(http.StatusNotFound, "user not exist in project")
return
}
//TODO: delete and insert should in one transaction
@ -179,7 +179,7 @@ func (pma *ProjectMemberAPI) Put() {
err = dao.DeleteUserProjectRoles(mid, pid)
if err != nil {
beego.Error("Failed to delete project roles for user, user id:", mid, ", project id: ", pid, ", error: ", err)
pma.RenderError(500, "Failed to update data in DB")
pma.RenderError(http.StatusInternalServerError, "Failed to update data in DB")
return
}
//insert roles in request
@ -187,7 +187,7 @@ func (pma *ProjectMemberAPI) Put() {
err = dao.AddUserProjectRole(mid, pid, int(rid))
if err != nil {
beego.Error("Failed to update DB to add project user role, project id:", pid, ", user id:", mid, ", role id:", rid)
pma.RenderError(500, "Failed to update data in database")
pma.RenderError(http.StatusInternalServerError, "Failed to update data in database")
return
}
}
@ -200,13 +200,13 @@ func (pma *ProjectMemberAPI) Delete() {
rolelist, err := dao.GetUserProjectRoles(userQuery, pid)
if len(rolelist) == 0 {
beego.Warning("Current user, id:", pma.currentUserId, ", does not have project admin role for project, id:", pid)
pma.RenderError(403, "")
pma.RenderError(http.StatusForbidden, "")
return
}
err = dao.DeleteUserProjectRoles(mid, pid)
if err != nil {
beego.Error("Failed to delete project roles for user, user id:", mid, ", project id:", pid, ", error:", err)
pma.RenderError(500, "Failed to update data in DB")
pma.RenderError(http.StatusInternalServerError, "Failed to update data in DB")
return
}
}

View File

@ -16,6 +16,7 @@ package api
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"time"
@ -56,28 +57,27 @@ func (ra *RepositoryAPI) Get() {
projectId, err0 := ra.GetInt64("project_id")
if err0 != nil {
beego.Error("Failed to get project id, error:", err0)
ra.RenderError(400, "Invalid project id")
ra.RenderError(http.StatusBadRequest, "Invalid project id")
return
}
projectQuery := models.Project{ProjectId: projectId}
p, err := dao.GetProjectById(projectQuery)
p, err := dao.GetProjectById(projectId)
if err != nil {
beego.Error("Error occurred in GetProjectById:", err)
ra.CustomAbort(500, "Internal error.")
ra.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if p == nil {
beego.Warning("Project with Id:", projectId, ", does not exist", projectId)
ra.RenderError(404, "")
ra.RenderError(http.StatusNotFound, "")
return
}
if p.Public == 0 && !CheckProjectPermission(ra.userId, projectId) {
ra.RenderError(403, "")
ra.RenderError(http.StatusForbidden, "")
return
}
repoList, err := svc_utils.GetRepoFromCache()
if err != nil {
beego.Error("Failed to get repo from cache, error:", err)
ra.RenderError(500, "internal sever error")
ra.RenderError(http.StatusInternalServerError, "internal sever error")
}
projectName := p.Name
q := ra.GetString("q")
@ -127,7 +127,7 @@ func (ra *RepositoryAPI) GetTags() {
result, err := svc_utils.RegistryApiGet(svc_utils.BuildRegistryUrl(repoName, "tags", "list"), ra.username)
if err != nil {
beego.Error("Failed to get repo tags, repo name:", repoName, ", error: ", err)
ra.RenderError(500, "Failed to get repo tags")
ra.RenderError(http.StatusInternalServerError, "Failed to get repo tags")
} else {
t := Tag{}
json.Unmarshal(result, &t)
@ -146,14 +146,14 @@ func (ra *RepositoryAPI) GetManifests() {
result, err := svc_utils.RegistryApiGet(svc_utils.BuildRegistryUrl(repoName, "manifests", tag), ra.username)
if err != nil {
beego.Error("Failed to get manifests for repo, repo name:", repoName, ", tag:", tag, ", error:", err)
ra.RenderError(500, "Internal Server Error")
ra.RenderError(http.StatusInternalServerError, "Internal Server Error")
return
} else {
mani := Manifest{}
err = json.Unmarshal(result, &mani)
if err != nil {
beego.Error("Failed to decode json from response for manifests, repo name:", repoName, ", tag:", tag, ", error:", err)
ra.RenderError(500, "Internal Server Error")
ra.RenderError(http.StatusInternalServerError, "Internal Server Error")
return
} else {
v1Compatibility := mani.History[0].V1Compatibility
@ -161,7 +161,7 @@ func (ra *RepositoryAPI) GetManifests() {
err = json.Unmarshal([]byte(v1Compatibility), &item)
if err != nil {
beego.Error("Failed to decode V1 field for repo, repo name:", repoName, ", tag:", tag, ", error:", err)
ra.RenderError(500, "Internal Server Error")
ra.RenderError(http.StatusInternalServerError, "Internal Server Error")
return
} else {
item.CreatedStr = item.Created.Format("2006-01-02 15:04:05")

View File

@ -15,6 +15,7 @@
package api
import (
"net/http"
"sort"
"strings"
@ -44,7 +45,7 @@ func (n *SearchAPI) Get() {
projects, err := dao.QueryRelevantProjects(userId)
if err != nil {
beego.Error("Failed to get projects of user id:", userId, ", error:", err)
n.CustomAbort(500, "Failed to get project search result")
n.CustomAbort(http.StatusInternalServerError, "Failed to get project search result")
}
projectSorter := &utils.ProjectSorter{Projects: projects}
sort.Sort(projectSorter)
@ -66,7 +67,7 @@ func (n *SearchAPI) Get() {
repositories, err2 := svc_utils.GetRepoFromCache()
if err2 != nil {
beego.Error("Failed to get repos from cache, error :", err2)
n.CustomAbort(500, "Failed to get repositories search result")
n.CustomAbort(http.StatusInternalServerError, "Failed to get repositories search result")
}
sort.Strings(repositories)
repositoryResult := filterRepositories(repositories, projects, keyword)

View File

@ -15,6 +15,7 @@
package api
import (
"net/http"
"strconv"
"github.com/vmware/harbor/dao"
@ -40,17 +41,17 @@ func (ua *UserAPI) Prepare() {
ua.userId, err = strconv.Atoi(id)
if err != nil {
beego.Error("Invalid user id, error:", err)
ua.CustomAbort(400, "Invalid user Id")
ua.CustomAbort(http.StatusBadRequest, "Invalid user Id")
}
userQuery := models.User{UserId: ua.userId}
u, err := dao.GetUser(userQuery)
if err != nil {
beego.Error("Error occurred in GetUser:", err)
ua.CustomAbort(500, "Internal error.")
ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if u == nil {
beego.Error("User with Id:", ua.userId, "does not exist")
ua.CustomAbort(404, "")
ua.CustomAbort(http.StatusNotFound, "")
}
}
}
@ -59,13 +60,13 @@ func (ua *UserAPI) Get() {
exist, err := dao.IsAdminRole(ua.currentUid)
if err != nil {
beego.Error("Error occurred in IsAdminRole:", err)
ua.CustomAbort(500, "Internal error.")
ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if ua.userId == 0 { //list users
if !exist {
beego.Error("Current user, id:", ua.currentUid, ", does not have admin role, can not list users")
ua.RenderError(403, "User does not have admin role")
ua.RenderError(http.StatusForbidden, "User does not have admin role")
return
}
username := ua.GetString("username")
@ -76,7 +77,7 @@ func (ua *UserAPI) Get() {
userList, err := dao.ListUsers(userQuery)
if err != nil {
beego.Error("Failed to get data from database, error:", err)
ua.RenderError(500, "Failed to query from database")
ua.RenderError(http.StatusInternalServerError, "Failed to query from database")
return
}
ua.Data["json"] = userList
@ -86,12 +87,12 @@ func (ua *UserAPI) Get() {
u, err := dao.GetUser(userQuery)
if err != nil {
beego.Error("Error occurred in GetUser:", err)
ua.CustomAbort(500, "Internal error.")
ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
ua.Data["json"] = u
} else {
beego.Error("Current user, id:", ua.currentUid, "does not have admin role, can not view other user's detail")
ua.RenderError(403, "User does not have admin role")
ua.RenderError(http.StatusForbidden, "User does not have admin role")
return
}
ua.ServeJSON()
@ -101,11 +102,11 @@ func (ua *UserAPI) Put() { //currently only for toggle admin, so no request body
exist, err := dao.IsAdminRole(ua.currentUid)
if err != nil {
beego.Error("Error occurred in IsAdminRole:", err)
ua.CustomAbort(500, "Internal error.")
ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if !exist {
beego.Warning("current user, id:", ua.currentUid, ", does not have admin role, can not update other user's role")
ua.RenderError(403, "User does not have admin role")
ua.RenderError(http.StatusForbidden, "User does not have admin role")
return
}
userQuery := models.User{UserId: ua.userId}
@ -116,17 +117,17 @@ func (ua *UserAPI) Delete() {
exist, err := dao.IsAdminRole(ua.currentUid)
if err != nil {
beego.Error("Error occurred in IsAdminRole:", err)
ua.CustomAbort(500, "Internal error.")
ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if !exist {
beego.Warning("current user, id:", ua.currentUid, ", does not have admin role, can not remove user")
ua.RenderError(403, "User does not have admin role")
ua.RenderError(http.StatusForbidden, "User does not have admin role")
return
}
err = dao.DeleteUser(ua.userId)
if err != nil {
beego.Error("Failed to delete data from database, error:", err)
ua.RenderError(500, "Failed to delete User")
ua.RenderError(http.StatusInternalServerError, "Failed to delete User")
return
}
}

View File

@ -15,6 +15,7 @@
package controllers
import (
"net/http"
"net/url"
"os"
@ -31,27 +32,27 @@ type ItemDetailController struct {
func (idc *ItemDetailController) Get() {
projectId, _ := idc.GetInt64("project_id")
if projectId <= 0 {
beego.Error("Invalid project id:", projectId)
idc.Redirect("/signIn", 302)
idc.Redirect("/signIn", http.StatusFound)
}
projectQuery := models.Project{ProjectId: projectId}
project, err := dao.GetProjectById(projectQuery)
project, err := dao.GetProjectById(projectId)
if err != nil {
beego.Error("Error occurred in GetProjectById:", err)
idc.CustomAbort(500, "Internal error.")
idc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if project == nil {
idc.Redirect("/signIn", 302)
idc.Redirect("/signIn", http.StatusFound)
}
sessionUserId := idc.GetSession("userId")
if project.Public != 1 && sessionUserId == nil {
idc.Redirect("/signIn?uri="+url.QueryEscape(idc.Ctx.Input.URI()), 302)
idc.Redirect("/signIn?uri="+url.QueryEscape(idc.Ctx.Input.URI()), http.StatusFound)
}
if sessionUserId != nil {
@ -62,11 +63,11 @@ func (idc *ItemDetailController) Get() {
roleList, err := dao.GetUserProjectRoles(models.User{UserId: sessionUserId.(int)}, projectId)
if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err)
idc.CustomAbort(500, "Internal error.")
idc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if project.Public == 0 && len(roleList) == 0 {
idc.Redirect("/signIn?uri="+url.QueryEscape(idc.Ctx.Input.URI()), 302)
idc.Redirect("/signIn?uri="+url.QueryEscape(idc.Ctx.Input.URI()), http.StatusFound)
} else if len(roleList) > 0 {
idc.Data["RoleId"] = roleList[0].RoleId
}

View File

@ -15,6 +15,8 @@
package controllers
import (
"net/http"
"github.com/vmware/harbor/models"
"github.com/vmware/harbor/opt_auth"
@ -45,11 +47,11 @@ func (c *CommonController) Login() {
user, err := opt_auth.Login(models.AuthModel{principal, password})
if err != nil {
beego.Error("Error occurred in UserLogin:", err)
c.CustomAbort(500, "Internal error.")
c.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if user == nil {
c.CustomAbort(401, "")
c.CustomAbort(http.StatusUnauthorized, "")
}
c.SetSession("userId", user.UserId)
@ -62,7 +64,7 @@ func (c *CommonController) SwitchLanguage() {
c.SetSession("lang", lang)
c.Data["Lang"] = lang
}
c.Redirect(c.Ctx.Request.Header.Get("Referer"), 302)
c.Redirect(c.Ctx.Request.Header.Get("Referer"), http.StatusFound)
}
func (c *CommonController) Logout() {

View File

@ -16,6 +16,7 @@ package controllers
import (
"bytes"
"net/http"
"os"
"regexp"
"text/template"
@ -34,7 +35,7 @@ type ChangePasswordController struct {
func (cpc *ChangePasswordController) Get() {
sessionUserId := cpc.GetSession("userId")
if sessionUserId == nil {
cpc.Redirect("/signIn", 302)
cpc.Redirect("/signIn", http.StatusFound)
}
cpc.Data["Username"] = cpc.GetSession("username")
cpc.ForwardTo("page_title_change_password", "change-password")
@ -46,25 +47,25 @@ func (cpc *CommonController) UpdatePassword() {
if sessionUserId == nil {
beego.Warning("User does not login.")
cpc.CustomAbort(401, "please_login_first")
cpc.CustomAbort(http.StatusUnauthorized, "please_login_first")
}
oldPassword := cpc.GetString("old_password")
if oldPassword == "" {
beego.Error("Old password is blank")
cpc.CustomAbort(400, "Old password is blank")
cpc.CustomAbort(http.StatusBadRequest, "Old password is blank")
}
queryUser := models.User{UserId: sessionUserId.(int), Password: oldPassword}
user, err := dao.CheckUserPassword(queryUser)
if err != nil {
beego.Error("Error occurred in CheckUserPassword:", err)
cpc.CustomAbort(500, "Internal error.")
cpc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if user == nil {
beego.Warning("Password input is not correct")
cpc.CustomAbort(403, "old_password_is_not_correct")
cpc.CustomAbort(http.StatusForbidden, "old_password_is_not_correct")
}
password := cpc.GetString("password")
@ -73,10 +74,10 @@ func (cpc *CommonController) UpdatePassword() {
err = dao.ChangeUserPassword(updateUser, oldPassword)
if err != nil {
beego.Error("Error occurred in ChangeUserPassword:", err)
cpc.CustomAbort(500, "Internal error.")
cpc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
} else {
cpc.CustomAbort(400, "please_input_new_password")
cpc.CustomAbort(http.StatusBadRequest, "please_input_new_password")
}
}
@ -101,23 +102,23 @@ func (fpc *CommonController) SendEmail() {
pass, _ := regexp.MatchString(`^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$`, email)
if !pass {
fpc.CustomAbort(400, "email_content_illegal")
fpc.CustomAbort(http.StatusBadRequest, "email_content_illegal")
} else {
queryUser := models.User{Email: email}
exist, err := dao.UserExists(queryUser, "email")
if err != nil {
beego.Error("Error occurred in UserExists:", err)
fpc.CustomAbort(500, "Internal error.")
fpc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if !exist {
fpc.CustomAbort(404, "email_does_not_exist")
fpc.CustomAbort(http.StatusNotFound, "email_does_not_exist")
}
messageTemplate, err := template.ParseFiles("views/reset-password-mail.tpl")
if err != nil {
beego.Error("Parse email template file failed:", err)
fpc.CustomAbort(500, err.Error())
fpc.CustomAbort(http.StatusInternalServerError, err.Error())
}
message := new(bytes.Buffer)
@ -129,7 +130,7 @@ func (fpc *CommonController) SendEmail() {
uuid, err := dao.GenerateRandomString()
if err != nil {
beego.Error("Error occurred in GenerateRandomString:", err)
fpc.CustomAbort(500, "Internal error.")
fpc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
err = messageTemplate.Execute(message, MessageDetail{
Hint: fpc.Tr("reset_email_hint"),
@ -139,13 +140,13 @@ func (fpc *CommonController) SendEmail() {
if err != nil {
beego.Error("message template error:", err)
fpc.CustomAbort(500, "internal_error")
fpc.CustomAbort(http.StatusInternalServerError, "internal_error")
}
config, err := beego.AppConfig.GetSection("mail")
if err != nil {
beego.Error("Can not load app.conf:", err)
fpc.CustomAbort(500, "internal_error")
fpc.CustomAbort(http.StatusInternalServerError, "internal_error")
}
mail := utils.Mail{
@ -158,7 +159,7 @@ func (fpc *CommonController) SendEmail() {
if err != nil {
beego.Error("send email failed:", err)
fpc.CustomAbort(500, "send_email_failed")
fpc.CustomAbort(http.StatusInternalServerError, "send_email_failed")
}
user := models.User{ResetUuid: uuid, Email: email}
@ -177,21 +178,21 @@ func (rpc *ResetPasswordController) Get() {
resetUuid := rpc.GetString("reset_uuid")
if resetUuid == "" {
beego.Error("Reset uuid is blank.")
rpc.Redirect("/", 302)
rpc.Redirect("/", http.StatusFound)
}
queryUser := models.User{ResetUuid: resetUuid}
user, err := dao.GetUser(queryUser)
if err != nil {
beego.Error("Error occurred in GetUser:", err)
rpc.CustomAbort(500, "Internal error.")
rpc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if user != nil {
rpc.Data["ResetUuid"] = user.ResetUuid
rpc.ForwardTo("page_title_reset_password", "reset-password")
} else {
rpc.Redirect("/", 302)
rpc.Redirect("/", http.StatusFound)
}
}
@ -199,18 +200,18 @@ func (rpc *CommonController) ResetPassword() {
resetUuid := rpc.GetString("reset_uuid")
if resetUuid == "" {
rpc.CustomAbort(400, "Reset uuid is blank.")
rpc.CustomAbort(http.StatusBadRequest, "Reset uuid is blank.")
}
queryUser := models.User{ResetUuid: resetUuid}
user, err := dao.GetUser(queryUser)
if err != nil {
beego.Error("Error occurred in GetUser:", err)
rpc.CustomAbort(500, "Internal error.")
rpc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if user == nil {
beego.Error("User does not exist")
rpc.CustomAbort(400, "User does not exist")
rpc.CustomAbort(http.StatusBadRequest, "User does not exist")
}
password := rpc.GetString("password")
@ -220,9 +221,9 @@ func (rpc *CommonController) ResetPassword() {
err = dao.ResetUserPassword(*user)
if err != nil {
beego.Error("Error occurred in ResetUserPassword:", err)
rpc.CustomAbort(500, "Internal error.")
rpc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
} else {
rpc.CustomAbort(400, "password_is_required")
rpc.CustomAbort(http.StatusBadRequest, "password_is_required")
}
}

View File

@ -15,6 +15,7 @@
package controllers
import (
"net/http"
"os"
"strings"
@ -33,7 +34,7 @@ func (rc *RegisterController) Get() {
if authMode == "" || authMode == "db_auth" {
rc.ForwardTo("page_title_registration", "register")
} else {
rc.Redirect("/signIn", 404)
rc.Redirect("/signIn", http.StatusNotFound)
}
}
@ -49,7 +50,7 @@ func (rc *CommonController) SignUp() {
_, err := dao.Register(user)
if err != nil {
beego.Error("Error occurred in Register:", err)
rc.CustomAbort(500, "Internal error.")
rc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
}
@ -68,7 +69,7 @@ func (rc *CommonController) UserExists() {
exist, err := dao.UserExists(user, target)
if err != nil {
beego.Error("Error occurred in UserExists:", err)
rc.CustomAbort(500, "Internal error.")
rc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
rc.Data["json"] = exist
rc.ServeJSON()

View File

@ -12,7 +12,7 @@
See the License for the specific language governing permissions and
limitations under the License.
*/
package test
package dao
import (
"fmt"
@ -22,7 +22,6 @@ import (
"testing"
"time"
"github.com/vmware/harbor/dao"
"github.com/vmware/harbor/models"
"github.com/astaxie/beego/orm"
@ -120,7 +119,7 @@ func TestMain(m *testing.M) {
os.Setenv("MYSQL_USR", dbUser)
os.Setenv("MYSQL_PWD", dbPassword)
os.Setenv("AUTH_MODE", "db_auth")
dao.InitDB()
InitDB()
clearUp(USERNAME)
os.Exit(m.Run())
@ -136,7 +135,7 @@ func TestRegister(t *testing.T) {
Comment: "register",
}
_, err := dao.Register(user)
_, err := Register(user)
if err != nil {
t.Errorf("Error occurred in Register: %v", err)
}
@ -145,7 +144,7 @@ func TestRegister(t *testing.T) {
queryUser := models.User{
Username: USERNAME,
}
newUser, err := dao.GetUser(queryUser)
newUser, err := GetUser(queryUser)
if err != nil {
t.Errorf("Error occurred in GetUser: %v", err)
}
@ -162,14 +161,14 @@ func TestUserExists(t *testing.T) {
var exists bool
var err error
exists, err = dao.UserExists(models.User{Username: USERNAME}, "username")
exists, err = UserExists(models.User{Username: USERNAME}, "username")
if err != nil {
t.Errorf("Error occurred in UserExists: %v", err)
}
if !exists {
t.Errorf("User %s was inserted but does not exist", USERNAME)
}
exists, err = dao.UserExists(models.User{Email: "tester01@vmware.com"}, "email")
exists, err = UserExists(models.User{Email: "tester01@vmware.com"}, "email")
if err != nil {
t.Errorf("Error occurred in UserExists: %v", err)
@ -177,7 +176,7 @@ func TestUserExists(t *testing.T) {
if !exists {
t.Errorf("User with email %s inserted but does not exist", "tester01@vmware.com")
}
exists, err = dao.UserExists(models.User{Username: "NOTHERE"}, "username")
exists, err = UserExists(models.User{Username: "NOTHERE"}, "username")
if err != nil {
t.Errorf("Error occurred in UserExists: %v", err)
}
@ -193,7 +192,7 @@ func TestLoginByUserName(t *testing.T) {
Password: "Abc12345",
}
loginUser, err := dao.LoginByDb(models.AuthModel{userQuery.Username, userQuery.Password})
loginUser, err := LoginByDb(models.AuthModel{userQuery.Username, userQuery.Password})
if err != nil {
t.Errorf("Error occurred in LoginByDb: %v", err)
}
@ -213,7 +212,7 @@ func TestLoginByEmail(t *testing.T) {
Password: "Abc12345",
}
loginUser, err := dao.LoginByDb(models.AuthModel{userQuery.Email, userQuery.Password})
loginUser, err := LoginByDb(models.AuthModel{userQuery.Email, userQuery.Password})
if err != nil {
t.Errorf("Error occurred in LoginByDb: %v", err)
}
@ -232,7 +231,7 @@ func TestGetUser(t *testing.T) {
Username: USERNAME,
}
var err error
currentUser, err = dao.GetUser(queryUser)
currentUser, err = GetUser(queryUser)
if err != nil {
t.Errorf("Error occurred in GetUser: %v", err)
}
@ -245,14 +244,14 @@ func TestGetUser(t *testing.T) {
}
func TestListUsers(t *testing.T) {
users, err := dao.ListUsers(models.User{})
users, err := ListUsers(models.User{})
if err != nil {
t.Errorf("Error occurred in ListUsers: %v", err)
}
if len(users) != 1 {
t.Errorf("Expect one user in list, but the acutal length is %d, the list: %+v", len(users), users)
}
users2, err := dao.ListUsers(models.User{Username: USERNAME})
users2, err := ListUsers(models.User{Username: USERNAME})
if len(users2) != 1 {
t.Errorf("Expect one user in list, but the acutal length is %d, the list: %+v", len(users), users)
}
@ -262,22 +261,22 @@ func TestListUsers(t *testing.T) {
}
func TestResetUserPassword(t *testing.T) {
uuid, err := dao.GenerateRandomString()
uuid, err := GenerateRandomString()
if err != nil {
t.Errorf("Error occurred in GenerateRandomString: %v", err)
}
err = dao.UpdateUserResetUuid(models.User{ResetUuid: uuid, Email: currentUser.Email})
err = UpdateUserResetUuid(models.User{ResetUuid: uuid, Email: currentUser.Email})
if err != nil {
t.Errorf("Error occurred in UpdateUserResetUuid: %v", err)
}
err = dao.ResetUserPassword(models.User{UserId: currentUser.UserId, Password: "HarborTester12345", ResetUuid: uuid, Salt: currentUser.Salt})
err = ResetUserPassword(models.User{UserId: currentUser.UserId, Password: "HarborTester12345", ResetUuid: uuid, Salt: currentUser.Salt})
if err != nil {
t.Errorf("Error occurred in ResetUserPassword: %v", err)
}
loginedUser, err := dao.LoginByDb(models.AuthModel{Principal: currentUser.Username, Password: "HarborTester12345"})
loginedUser, err := LoginByDb(models.AuthModel{Principal: currentUser.Username, Password: "HarborTester12345"})
if err != nil {
t.Errorf("Error occurred in LoginByDb: %v", err)
}
@ -288,12 +287,12 @@ func TestResetUserPassword(t *testing.T) {
}
func TestChangeUserPassword(t *testing.T) {
err := dao.ChangeUserPassword(models.User{UserId: currentUser.UserId, Password: "NewHarborTester12345", Salt: currentUser.Salt})
err := ChangeUserPassword(models.User{UserId: currentUser.UserId, Password: "NewHarborTester12345", Salt: currentUser.Salt})
if err != nil {
t.Errorf("Error occurred in ChangeUserPassword: %v", err)
}
loginedUser, err := dao.LoginByDb(models.AuthModel{Principal: currentUser.Username, Password: "NewHarborTester12345"})
loginedUser, err := LoginByDb(models.AuthModel{Principal: currentUser.Username, Password: "NewHarborTester12345"})
if err != nil {
t.Errorf("Error occurred in LoginByDb: %v", err)
}
@ -304,11 +303,11 @@ func TestChangeUserPassword(t *testing.T) {
}
func TestChangeUserPasswordWithOldPassword(t *testing.T) {
err := dao.ChangeUserPassword(models.User{UserId: currentUser.UserId, Password: "NewerHarborTester12345", Salt: currentUser.Salt}, "NewHarborTester12345")
err := ChangeUserPassword(models.User{UserId: currentUser.UserId, Password: "NewerHarborTester12345", Salt: currentUser.Salt}, "NewHarborTester12345")
if err != nil {
t.Errorf("Error occurred in ChangeUserPassword: %v", err)
}
loginedUser, err := dao.LoginByDb(models.AuthModel{Principal: currentUser.Username, Password: "NewerHarborTester12345"})
loginedUser, err := LoginByDb(models.AuthModel{Principal: currentUser.Username, Password: "NewerHarborTester12345"})
if err != nil {
t.Errorf("Error occurred in LoginByDb: %v", err)
}
@ -318,11 +317,11 @@ func TestChangeUserPasswordWithOldPassword(t *testing.T) {
}
func TestChangeUserPasswordWithIncorrectOldPassword(t *testing.T) {
err := dao.ChangeUserPassword(models.User{UserId: currentUser.UserId, Password: "NNewerHarborTester12345", Salt: currentUser.Salt}, "WrongNewerHarborTester12345")
err := ChangeUserPassword(models.User{UserId: currentUser.UserId, Password: "NNewerHarborTester12345", Salt: currentUser.Salt}, "WrongNewerHarborTester12345")
if err == nil {
t.Errorf("Error does not occurred due to old password is incorrect.")
}
loginedUser, err := dao.LoginByDb(models.AuthModel{Principal: currentUser.Username, Password: "NNewerHarborTester12345"})
loginedUser, err := LoginByDb(models.AuthModel{Principal: currentUser.Username, Password: "NNewerHarborTester12345"})
if err != nil {
t.Errorf("Error occurred in LoginByDb: %v", err)
}
@ -332,7 +331,7 @@ func TestChangeUserPasswordWithIncorrectOldPassword(t *testing.T) {
}
func TestQueryRelevantProjectsWhenNoProjectAdded(t *testing.T) {
projects, err := dao.QueryRelevantProjects(currentUser.UserId)
projects, err := QueryRelevantProjects(currentUser.UserId)
if err != nil {
t.Errorf("Error occurred in QueryRelevantProjects: %v", err)
}
@ -353,12 +352,12 @@ func TestAddProject(t *testing.T) {
OwnerName: currentUser.Username,
}
err := dao.AddProject(project)
err := AddProject(project)
if err != nil {
t.Errorf("Error occurred in AddProject: %v", err)
}
newProject, err := dao.GetProjectByName(PROJECT_NAME)
newProject, err := GetProjectByName(PROJECT_NAME)
if err != nil {
t.Errorf("Error occurred in GetProjectByName: %v", err)
}
@ -371,7 +370,7 @@ var currentProject *models.Project
func TestGetProject(t *testing.T) {
var err error
currentProject, err = dao.GetProjectByName(PROJECT_NAME)
currentProject, err = GetProjectByName(PROJECT_NAME)
if err != nil {
t.Errorf("Error occurred in GetProjectByName: %v", err)
}
@ -414,7 +413,7 @@ func TestGetAccessLog(t *testing.T) {
UserId: currentUser.UserId,
ProjectId: currentProject.ProjectId,
}
accessLogs, err := dao.GetAccessLogs(queryAccessLog)
accessLogs, err := GetAccessLogs(queryAccessLog)
if err != nil {
t.Errorf("Error occurred in GetAccessLog: %v", err)
}
@ -429,14 +428,14 @@ func TestGetAccessLog(t *testing.T) {
func TestProjectExists(t *testing.T) {
var exists bool
var err error
exists, err = dao.ProjectExists(currentProject.ProjectId)
exists, err = ProjectExists(currentProject.ProjectId)
if err != nil {
t.Errorf("Error occurred in ProjectExists: %v", err)
}
if !exists {
t.Errorf("The project with id: %d, does not exist", currentProject.ProjectId)
}
exists, err = dao.ProjectExists(currentProject.Name)
exists, err = ProjectExists(currentProject.Name)
if err != nil {
t.Errorf("Error occurred in ProjectExists: %v", err)
}
@ -445,25 +444,61 @@ func TestProjectExists(t *testing.T) {
}
}
func TestGetProjectById(t *testing.T) {
id := currentProject.ProjectId
p, err := GetProjectById(id)
if err != nil {
t.Errorf("Error in GetProjectById: %v, id: %d", err, id)
}
if p.Name != currentProject.Name {
t.Errorf("project name does not match, expected: %s, actual: %s", currentProject.Name, p.Name)
}
}
func TestGetUserByProject(t *testing.T) {
pid := currentProject.ProjectId
u1 := models.User{
Username: "%%Tester%%",
}
u2 := models.User{
Username: "nononono",
}
users, err := GetUserByProject(pid, u1)
if err != nil {
t.Errorf("Error happened in GetUserByProject: %v, project Id: %d, user: %+v", u1)
}
if len(users) != 1 {
t.Errorf("unexpected length of user list, expected: 1, the users list: %+v", users)
}
users, err = GetUserByProject(pid, u2)
if err != nil {
t.Errorf("Error happened in GetUserByProject: %v, project Id: %d, user: %+v", u2)
}
if len(users) != 0 {
t.Errorf("unexpected length of user list, expected: 0, the users list: %+v", users)
}
}
func TestToggleProjectPublicity(t *testing.T) {
err := dao.ToggleProjectPublicity(currentProject.ProjectId, PUBLICITY_ON)
err := ToggleProjectPublicity(currentProject.ProjectId, PUBLICITY_ON)
if err != nil {
t.Errorf("Error occurred in ToggleProjectPublicity: %v", err)
}
currentProject, err = dao.GetProjectByName(PROJECT_NAME)
currentProject, err = GetProjectByName(PROJECT_NAME)
if err != nil {
t.Errorf("Error occurred in GetProjectByName: %v", err)
}
if currentProject.Public != PUBLICITY_ON {
t.Errorf("project, id: %d, its publicity is not on", currentProject.ProjectId)
}
err = dao.ToggleProjectPublicity(currentProject.ProjectId, PUBLICITY_OFF)
err = ToggleProjectPublicity(currentProject.ProjectId, PUBLICITY_OFF)
if err != nil {
t.Errorf("Error occurred in ToggleProjectPublicity: %v", err)
}
currentProject, err = dao.GetProjectByName(PROJECT_NAME)
currentProject, err = GetProjectByName(PROJECT_NAME)
if err != nil {
t.Errorf("Error occurred in GetProjectByName: %v", err)
}
@ -471,6 +506,47 @@ func TestToggleProjectPublicity(t *testing.T) {
if currentProject.Public != PUBLICITY_OFF {
t.Errorf("project, id: %d, its publicity is not off", currentProject.ProjectId)
}
}
func TestIsProjectPublic(t *testing.T) {
if isPublic := IsProjectPublic(PROJECT_NAME); isPublic {
t.Errorf("project, id: %d, its publicity is not false after turning off", currentProject.ProjectId)
}
}
func TestQueryProject(t *testing.T) {
query1 := models.Project{
UserId: 1,
}
projects, err := QueryProject(query1)
if err != nil {
t.Errorf("Error in Query Project: %v, query: %+v", err, query1)
}
if len(projects) != 2 {
t.Errorf("Expecting get 2 projects, but actual: %d, the list: %+v", len(projects), projects)
}
query2 := models.Project{
Public: 1,
}
projects, err = QueryProject(query2)
if err != nil {
t.Errorf("Error in Query Project: %v, query: %+v", err, query2)
}
if len(projects) != 1 {
t.Errorf("Expecting get 1 project, but actual: %d, the list: %+v", len(projects), projects)
}
query3 := models.Project{
UserId: 9,
}
projects, err = QueryProject(query3)
if err != nil {
t.Errorf("Error in Query Project: %v, query: %+v", err, query3)
}
if len(projects) != 0 {
t.Errorf("Expecting get 0 project, but actual: %d, the list: %+v", len(projects), projects)
}
}
func getUserProjectRole(projectId int64, userId int) []models.Role {
@ -487,8 +563,12 @@ func getUserProjectRole(projectId int64, userId int) []models.Role {
return r
}
func TestGetUserProjectRole(t *testing.T) {
r := getUserProjectRole(currentProject.ProjectId, currentUser.UserId)
func TestGetUserProjectRoles(t *testing.T) {
user := *currentUser
r, err := GetUserProjectRoles(user, currentProject.ProjectId)
if err != nil {
t.Errorf("Error happened in GetUserProjectRole: %v, user: %+v, project Id: %d", err, user, currentProject.ProjectId)
}
//Get the size of current user project role.
if len(r) != 1 {
@ -498,10 +578,20 @@ func TestGetUserProjectRole(t *testing.T) {
if r[0].Name != "projectAdmin" {
t.Errorf("the expected rolename is: projectAdmin, actual: %s", r[0].Name)
}
user.RoleId = 1
r, err = GetUserProjectRoles(user, currentProject.ProjectId)
if err != nil {
t.Errorf("Error happened in GetUserProjectRole: %v, user: %+v, project Id: %d", err, user, currentProject.ProjectId)
}
//Get the size of current user project role.
if len(r) != 0 {
t.Errorf("The user, id: %d, should not have role id: 1 in project id: %d, actual role list: %v", currentUser.UserId, currentProject.ProjectId, r)
}
}
func TestProjectPermission(t *testing.T) {
roleCode, err := dao.GetPermission(currentUser.Username, currentProject.Name)
roleCode, err := GetPermission(currentUser.Username, currentProject.Name)
if err != nil {
t.Errorf("Error occurred in GetPermission: %v", err)
}
@ -511,7 +601,7 @@ func TestProjectPermission(t *testing.T) {
}
func TestQueryRelevantProjects(t *testing.T) {
projects, err := dao.QueryRelevantProjects(currentUser.UserId)
projects, err := QueryRelevantProjects(currentUser.UserId)
if err != nil {
t.Errorf("Error occurred in QueryRelevantProjects: %v", err)
}
@ -524,7 +614,7 @@ func TestQueryRelevantProjects(t *testing.T) {
}
func TestAssignUserProjectRole(t *testing.T) {
err := dao.AddUserProjectRole(currentUser.UserId, currentProject.ProjectId, DEVELOPER)
err := AddUserProjectRole(currentUser.UserId, currentProject.ProjectId, DEVELOPER)
if err != nil {
t.Errorf("Error occurred in AddUserProjectRole: %v", err)
}
@ -542,7 +632,7 @@ func TestAssignUserProjectRole(t *testing.T) {
}
func TestDeleteUserProjectRole(t *testing.T) {
err := dao.DeleteUserProjectRoles(currentUser.UserId, currentProject.ProjectId)
err := DeleteUserProjectRoles(currentUser.UserId, currentProject.ProjectId)
if err != nil {
t.Errorf("Error occurred in DeleteUserProjectRoles: %v", err)
}
@ -554,12 +644,37 @@ func TestDeleteUserProjectRole(t *testing.T) {
}
}
func TestToggleAdminRole(t *testing.T) {
err := ToggleUserAdminRole(*currentUser)
if err != nil {
t.Errorf("Error in toggle ToggleUserAdmin role: %v, user: %+v", err, currentUser)
}
isAdmin, err := IsAdminRole(currentUser.UserId)
if err != nil {
t.Errorf("Error in IsAdminRole: %v, user id: %d", err, currentUser.UserId)
}
if !isAdmin {
t.Errorf("User is not admin after toggled, user id: %d", currentUser.UserId)
}
err = ToggleUserAdminRole(*currentUser)
if err != nil {
t.Errorf("Error in toggle ToggleUserAdmin role: %v, user: %+v", err, currentUser)
}
isAdmin, err = IsAdminRole(currentUser.UserId)
if err != nil {
t.Errorf("Error in IsAdminRole: %v, user id: %d", err, currentUser.UserId)
}
if isAdmin {
t.Errorf("User is still admin after toggled, user id: %d", currentUser.UserId)
}
}
func TestDeleteUser(t *testing.T) {
err := dao.DeleteUser(currentUser.UserId)
err := DeleteUser(currentUser.UserId)
if err != nil {
t.Errorf("Error occurred in DeleteUser: %v", err)
}
user, err := dao.GetUser(*currentUser)
user, err := GetUser(*currentUser)
if err != nil {
t.Errorf("Error occurred in GetUser: %v", err)
}

View File

@ -20,7 +20,7 @@ import (
"github.com/astaxie/beego/orm"
)
func GetUserByProject(queryProject models.Project, queryUser models.User) ([]models.User, error) {
func GetUserByProject(projectId int64, queryUser models.User) ([]models.User, error) {
o := orm.NewOrm()
u := []models.User{}
sql := `select
@ -35,14 +35,11 @@ func GetUserByProject(queryProject models.Project, queryUser models.User) ([]mod
and pr.project_id = ? `
queryParam := make([]interface{}, 1)
queryParam = append(queryParam, queryProject.ProjectId)
queryParam = append(queryParam, projectId)
if queryUser.Username != "" {
sql += " and u.username like ? "
queryParam = append(queryParam, queryUser.Username)
} else if queryUser.RoleId != 0 {
sql += ` and r.role_id <= ? `
queryParam = append(queryParam, queryUser.RoleId)
}
sql += ` order by u.user_id `
_, err := o.Raw(sql, queryParam).QueryRows(&u)

View File

@ -94,6 +94,7 @@ func IsProjectPublic(projectName string) bool {
return project.Public == 1
}
//Query the projects based on publicity and user, disregarding the names etc.
func QueryProject(query models.Project) ([]models.Project, error) {
o := orm.NewOrm()
@ -154,17 +155,13 @@ func ProjectExists(nameOrId interface{}) (bool, error) {
}
func GetProjectById(query models.Project) (*models.Project, error) {
func GetProjectById(projectId int64) (*models.Project, error) {
o := orm.NewOrm()
sql := `select p.project_id, p.name, u.username as owner_name, p.owner_id, p.creation_time, p.public
from project p left join user u on p.owner_id = u.user_id where p.deleted = 0 and p.project_id = ?`
queryParam := make([]interface{}, 1)
queryParam = append(queryParam, query.ProjectId)
if query.Public != 0 {
sql += " and p.public = ? "
queryParam = append(queryParam, query.Public)
}
queryParam = append(queryParam, projectId)
p := []models.Project{}
count, err := o.Raw(sql, queryParam).QueryRows(&p)

View File

@ -16,6 +16,7 @@ package service
import (
"log"
"net/http"
"github.com/vmware/harbor/models"
"github.com/vmware/harbor/opt_auth"
@ -46,7 +47,7 @@ func (a *AuthController) Auth() {
if len(scope) == 0 && !authenticated {
log.Printf("login request with invalid credentials")
a.CustomAbort(401, "")
a.CustomAbort(http.StatusUnauthorized, "")
}
access := svc_utils.GetResourceActions(scope)
for _, a := range access {
@ -61,7 +62,7 @@ func (a *AuthController) serveToken(username, service string, access []*token.Re
rawToken, err := svc_utils.MakeToken(username, service, access)
if err != nil {
log.Printf("Failed to make token, error: %v", err)
writer.WriteHeader(500)
writer.WriteHeader(http.StatusInternalServerError)
return
}
tk := make(map[string]string)

View File

@ -50,9 +50,9 @@ func RegistryApiGet(url, username string) ([]byte, error) {
return nil, err
}
defer response.Body.Close()
if response.StatusCode == 200 {
if response.StatusCode == http.StatusOK {
return result, nil
} else if response.StatusCode == 401 {
} else if response.StatusCode == http.StatusUnauthorized {
authenticate := response.Header.Get("WWW-Authenticate")
str := strings.Split(authenticate, " ")[1]
log.Println("url: " + url)
@ -94,7 +94,7 @@ func RegistryApiGet(url, username string) ([]byte, error) {
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
if response.StatusCode != http.StatusOK {
errMsg := fmt.Sprintf("Unexpected return code from registry: %d", response.StatusCode)
log.Printf(errMsg)
return nil, fmt.Errorf(errMsg)

View File

@ -55,9 +55,9 @@ func HttpGet(url, sessionId, username, password string) ([]byte, error) {
return nil, err
}
defer response.Body.Close()
if response.StatusCode == 200 {
if response.StatusCode == http.StatusOK {
return result, nil
} else if response.StatusCode == 401 {
} else if response.StatusCode == http.StatusUnauthorized {
authenticate := response.Header.Get("WWW-Authenticate")
str := strings.Split(authenticate, " ")[1]
beego.Trace("url: " + url)
@ -106,7 +106,7 @@ func HttpGet(url, sessionId, username, password string) ([]byte, error) {
if err != nil {
return nil, err
}
if response.StatusCode == 200 {
if response.StatusCode == http.StatusOK {
tt := make(map[string]string)
json.Unmarshal(result, &tt)
request, err = http.NewRequest("GET", url, nil)