Merge pull request #11 from ywk253100/golint_refactor

golint refactor for controller and service
This commit is contained in:
reasonerjt 2016-02-25 14:43:45 +08:00
commit 6b31b740a2
9 changed files with 103 additions and 103 deletions

View File

@ -124,7 +124,7 @@ func (ra *RepositoryAPI) GetTags() {
var tags []string var tags []string
repoName := ra.GetString("repo_name") repoName := ra.GetString("repo_name")
result, err := svc_utils.RegistryApiGet(svc_utils.BuildRegistryUrl(repoName, "tags", "list"), ra.username) result, err := svc_utils.RegistryAPIGet(svc_utils.BuildRegistryURL(repoName, "tags", "list"), ra.username)
if err != nil { if err != nil {
beego.Error("Failed to get repo tags, repo name:", repoName, ", error: ", err) beego.Error("Failed to get repo tags, repo name:", repoName, ", error: ", err)
ra.RenderError(http.StatusInternalServerError, "Failed to get repo tags") ra.RenderError(http.StatusInternalServerError, "Failed to get repo tags")
@ -143,7 +143,7 @@ func (ra *RepositoryAPI) GetManifests() {
item := models.RepoItem{} item := models.RepoItem{}
result, err := svc_utils.RegistryApiGet(svc_utils.BuildRegistryUrl(repoName, "manifests", tag), ra.username) result, err := svc_utils.RegistryAPIGet(svc_utils.BuildRegistryURL(repoName, "manifests", tag), ra.username)
if err != nil { if err != nil {
beego.Error("Failed to get manifests for repo, repo name:", repoName, ", tag:", tag, ", error:", err) beego.Error("Failed to get manifests for repo, repo name:", repoName, ", tag:", tag, ", error:", err)
ra.RenderError(http.StatusInternalServerError, "Internal Server Error") ra.RenderError(http.StatusInternalServerError, "Internal Server Error")

View File

@ -42,14 +42,14 @@ type langType struct {
} }
const ( const (
DEFAULT_LANG = "en-US" defaultLang = "en-US"
) )
var supportLanguages map[string]langType var supportLanguages map[string]langType
func (b *BaseController) Prepare() { func (b *BaseController) Prepare() {
var lang string = "" var lang string
al := b.Ctx.Request.Header.Get("Accept-Language") al := b.Ctx.Request.Header.Get("Accept-Language")
if len(al) > 4 { if len(al) > 4 {
@ -60,7 +60,7 @@ func (b *BaseController) Prepare() {
} }
if _, exist := supportLanguages[lang]; exist == false { //Check if support the request language. if _, exist := supportLanguages[lang]; exist == false { //Check if support the request language.
lang = DEFAULT_LANG //Set default language if not supported. lang = defaultLang //Set default language if not supported.
} }
sessionLang := b.GetSession("lang") sessionLang := b.GetSession("lang")
@ -88,8 +88,8 @@ func (b *BaseController) Prepare() {
b.Data["CurLang"] = curLang.Name b.Data["CurLang"] = curLang.Name
b.Data["RestLangs"] = restLangs b.Data["RestLangs"] = restLangs
sessionUserId := b.GetSession("userId") sessionUserID := b.GetSession("userId")
if sessionUserId != nil { if sessionUserID != nil {
b.Data["Username"] = b.GetSession("username") b.Data["Username"] = b.GetSession("username")
} }
authMode := os.Getenv("AUTH_MODE") authMode := os.Getenv("AUTH_MODE")

View File

@ -31,15 +31,15 @@ type ItemDetailController struct {
func (idc *ItemDetailController) Get() { func (idc *ItemDetailController) Get() {
projectId, _ := idc.GetInt64("project_id") projectID, _ := idc.GetInt64("project_id")
if projectId <= 0 { if projectID <= 0 {
beego.Error("Invalid project id:", projectId) beego.Error("Invalid project id:", projectID)
idc.Redirect("/signIn", http.StatusFound) idc.Redirect("/signIn", http.StatusFound)
return return
} }
project, err := dao.GetProjectById(projectId) project, err := dao.GetProjectById(projectID)
if err != nil { if err != nil {
beego.Error("Error occurred in GetProjectById:", err) beego.Error("Error occurred in GetProjectById:", err)
@ -51,19 +51,19 @@ func (idc *ItemDetailController) Get() {
return return
} }
sessionUserId := idc.GetSession("userId") sessionUserID := idc.GetSession("userId")
if project.Public != 1 && sessionUserId == nil { if project.Public != 1 && sessionUserID == nil {
idc.Redirect("/signIn?uri="+url.QueryEscape(idc.Ctx.Input.URI()), http.StatusFound) idc.Redirect("/signIn?uri="+url.QueryEscape(idc.Ctx.Input.URI()), http.StatusFound)
return return
} }
if sessionUserId != nil { if sessionUserID != nil {
idc.Data["Username"] = idc.GetSession("username") idc.Data["Username"] = idc.GetSession("username")
idc.Data["UserId"] = sessionUserId.(int) idc.Data["UserId"] = sessionUserID.(int)
roleList, err := dao.GetUserProjectRoles(models.User{UserId: sessionUserId.(int)}, projectId) roleList, err := dao.GetUserProjectRoles(models.User{UserId: sessionUserID.(int)}, projectID)
if err != nil { if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err) beego.Error("Error occurred in GetUserProjectRoles:", err)
idc.CustomAbort(http.StatusInternalServerError, "Internal error.") idc.CustomAbort(http.StatusInternalServerError, "Internal error.")

View File

@ -33,8 +33,8 @@ type ChangePasswordController struct {
} }
func (cpc *ChangePasswordController) Get() { func (cpc *ChangePasswordController) Get() {
sessionUserId := cpc.GetSession("userId") sessionUserID := cpc.GetSession("userId")
if sessionUserId == nil { if sessionUserID == nil {
cpc.Redirect("/signIn", http.StatusFound) cpc.Redirect("/signIn", http.StatusFound)
return return
} }
@ -42,43 +42,43 @@ func (cpc *ChangePasswordController) Get() {
cpc.ForwardTo("page_title_change_password", "change-password") cpc.ForwardTo("page_title_change_password", "change-password")
} }
func (cpc *CommonController) UpdatePassword() { func (cc *CommonController) UpdatePassword() {
sessionUserId := cpc.GetSession("userId") sessionUserID := cc.GetSession("userId")
if sessionUserId == nil { if sessionUserID == nil {
beego.Warning("User does not login.") beego.Warning("User does not login.")
cpc.CustomAbort(http.StatusUnauthorized, "please_login_first") cc.CustomAbort(http.StatusUnauthorized, "please_login_first")
} }
oldPassword := cpc.GetString("old_password") oldPassword := cc.GetString("old_password")
if oldPassword == "" { if oldPassword == "" {
beego.Error("Old password is blank") beego.Error("Old password is blank")
cpc.CustomAbort(http.StatusBadRequest, "Old password is blank") cc.CustomAbort(http.StatusBadRequest, "Old password is blank")
} }
queryUser := models.User{UserId: sessionUserId.(int), Password: oldPassword} queryUser := models.User{UserId: sessionUserID.(int), Password: oldPassword}
user, err := dao.CheckUserPassword(queryUser) user, err := dao.CheckUserPassword(queryUser)
if err != nil { if err != nil {
beego.Error("Error occurred in CheckUserPassword:", err) beego.Error("Error occurred in CheckUserPassword:", err)
cpc.CustomAbort(http.StatusInternalServerError, "Internal error.") cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
} }
if user == nil { if user == nil {
beego.Warning("Password input is not correct") beego.Warning("Password input is not correct")
cpc.CustomAbort(http.StatusForbidden, "old_password_is_not_correct") cc.CustomAbort(http.StatusForbidden, "old_password_is_not_correct")
} }
password := cpc.GetString("password") password := cc.GetString("password")
if password != "" { if password != "" {
updateUser := models.User{UserId: sessionUserId.(int), Password: password, Salt: user.Salt} updateUser := models.User{UserId: sessionUserID.(int), Password: password, Salt: user.Salt}
err = dao.ChangeUserPassword(updateUser, oldPassword) err = dao.ChangeUserPassword(updateUser, oldPassword)
if err != nil { if err != nil {
beego.Error("Error occurred in ChangeUserPassword:", err) beego.Error("Error occurred in ChangeUserPassword:", err)
cpc.CustomAbort(http.StatusInternalServerError, "Internal error.") cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
} }
} else { } else {
cpc.CustomAbort(http.StatusBadRequest, "please_input_new_password") cc.CustomAbort(http.StatusBadRequest, "please_input_new_password")
} }
} }
@ -88,79 +88,79 @@ type ForgotPasswordController struct {
type MessageDetail struct { type MessageDetail struct {
Hint string Hint string
Url string URL string
Uuid string UUID string
} }
func (fpc *ForgotPasswordController) Get() { func (fpc *ForgotPasswordController) Get() {
fpc.ForwardTo("page_title_forgot_password", "forgot-password") fpc.ForwardTo("page_title_forgot_password", "forgot-password")
} }
func (fpc *CommonController) SendEmail() { func (cc *CommonController) SendEmail() {
email := fpc.GetString("email") email := cc.GetString("email")
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) 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 { if !pass {
fpc.CustomAbort(http.StatusBadRequest, "email_content_illegal") cc.CustomAbort(http.StatusBadRequest, "email_content_illegal")
} else { } else {
queryUser := models.User{Email: email} queryUser := models.User{Email: email}
exist, err := dao.UserExists(queryUser, "email") exist, err := dao.UserExists(queryUser, "email")
if err != nil { if err != nil {
beego.Error("Error occurred in UserExists:", err) beego.Error("Error occurred in UserExists:", err)
fpc.CustomAbort(http.StatusInternalServerError, "Internal error.") cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
} }
if !exist { if !exist {
fpc.CustomAbort(http.StatusNotFound, "email_does_not_exist") cc.CustomAbort(http.StatusNotFound, "email_does_not_exist")
} }
messageTemplate, err := template.ParseFiles("views/reset-password-mail.tpl") messageTemplate, err := template.ParseFiles("views/reset-password-mail.tpl")
if err != nil { if err != nil {
beego.Error("Parse email template file failed:", err) beego.Error("Parse email template file failed:", err)
fpc.CustomAbort(http.StatusInternalServerError, err.Error()) cc.CustomAbort(http.StatusInternalServerError, err.Error())
} }
message := new(bytes.Buffer) message := new(bytes.Buffer)
harborUrl := os.Getenv("HARBOR_URL") harborURL := os.Getenv("HARBOR_URL")
if harborUrl == "" { if harborURL == "" {
harborUrl = "localhost" harborURL = "localhost"
} }
uuid, err := dao.GenerateRandomString() uuid, err := dao.GenerateRandomString()
if err != nil { if err != nil {
beego.Error("Error occurred in GenerateRandomString:", err) beego.Error("Error occurred in GenerateRandomString:", err)
fpc.CustomAbort(http.StatusInternalServerError, "Internal error.") cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
} }
err = messageTemplate.Execute(message, MessageDetail{ err = messageTemplate.Execute(message, MessageDetail{
Hint: fpc.Tr("reset_email_hint"), Hint: cc.Tr("reset_email_hint"),
Url: harborUrl, URL: harborURL,
Uuid: uuid, UUID: uuid,
}) })
if err != nil { if err != nil {
beego.Error("message template error:", err) beego.Error("message template error:", err)
fpc.CustomAbort(http.StatusInternalServerError, "internal_error") cc.CustomAbort(http.StatusInternalServerError, "internal_error")
} }
config, err := beego.AppConfig.GetSection("mail") config, err := beego.AppConfig.GetSection("mail")
if err != nil { if err != nil {
beego.Error("Can not load app.conf:", err) beego.Error("Can not load app.conf:", err)
fpc.CustomAbort(http.StatusInternalServerError, "internal_error") cc.CustomAbort(http.StatusInternalServerError, "internal_error")
} }
mail := utils.Mail{ mail := utils.Mail{
From: config["from"], From: config["from"],
To: []string{email}, To: []string{email},
Subject: fpc.Tr("reset_email_subject"), Subject: cc.Tr("reset_email_subject"),
Message: message.String()} Message: message.String()}
err = mail.SendMail() err = mail.SendMail()
if err != nil { if err != nil {
beego.Error("send email failed:", err) beego.Error("send email failed:", err)
fpc.CustomAbort(http.StatusInternalServerError, "send_email_failed") cc.CustomAbort(http.StatusInternalServerError, "send_email_failed")
} }
user := models.User{ResetUuid: uuid, Email: email} user := models.User{ResetUuid: uuid, Email: email}
@ -176,14 +176,14 @@ type ResetPasswordController struct {
func (rpc *ResetPasswordController) Get() { func (rpc *ResetPasswordController) Get() {
resetUuid := rpc.GetString("reset_uuid") resetUUID := rpc.GetString("reset_uuid")
if resetUuid == "" { if resetUUID == "" {
beego.Error("Reset uuid is blank.") beego.Error("Reset uuid is blank.")
rpc.Redirect("/", http.StatusFound) rpc.Redirect("/", http.StatusFound)
return return
} }
queryUser := models.User{ResetUuid: resetUuid} queryUser := models.User{ResetUuid: resetUUID}
user, err := dao.GetUser(queryUser) user, err := dao.GetUser(queryUser)
if err != nil { if err != nil {
beego.Error("Error occurred in GetUser:", err) beego.Error("Error occurred in GetUser:", err)
@ -198,34 +198,34 @@ func (rpc *ResetPasswordController) Get() {
} }
} }
func (rpc *CommonController) ResetPassword() { func (cc *CommonController) ResetPassword() {
resetUuid := rpc.GetString("reset_uuid") resetUUID := cc.GetString("reset_uuid")
if resetUuid == "" { if resetUUID == "" {
rpc.CustomAbort(http.StatusBadRequest, "Reset uuid is blank.") cc.CustomAbort(http.StatusBadRequest, "Reset uuid is blank.")
} }
queryUser := models.User{ResetUuid: resetUuid} queryUser := models.User{ResetUuid: resetUUID}
user, err := dao.GetUser(queryUser) user, err := dao.GetUser(queryUser)
if err != nil { if err != nil {
beego.Error("Error occurred in GetUser:", err) beego.Error("Error occurred in GetUser:", err)
rpc.CustomAbort(http.StatusInternalServerError, "Internal error.") cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
} }
if user == nil { if user == nil {
beego.Error("User does not exist") beego.Error("User does not exist")
rpc.CustomAbort(http.StatusBadRequest, "User does not exist") cc.CustomAbort(http.StatusBadRequest, "User does not exist")
} }
password := rpc.GetString("password") password := cc.GetString("password")
if password != "" { if password != "" {
user.Password = password user.Password = password
err = dao.ResetUserPassword(*user) err = dao.ResetUserPassword(*user)
if err != nil { if err != nil {
beego.Error("Error occurred in ResetUserPassword:", err) beego.Error("Error occurred in ResetUserPassword:", err)
rpc.CustomAbort(http.StatusInternalServerError, "Internal error.") cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
} }
} else { } else {
rpc.CustomAbort(http.StatusBadRequest, "password_is_required") cc.CustomAbort(http.StatusBadRequest, "password_is_required")
} }
} }

View File

@ -79,7 +79,7 @@ func authenticate(principal, password string) bool {
} }
if user == nil { if user == nil {
return false return false
} else { }
return true return true
} }
}

View File

@ -29,7 +29,7 @@ type NotificationHandler struct {
beego.Controller beego.Controller
} }
const MEDIA_TYPE_MANIFEST = "application/vnd.docker.distribution.manifest.v1+json" const MediaTypeManifest = "application/vnd.docker.distribution.manifest.v1+json"
func (n *NotificationHandler) Post() { func (n *NotificationHandler) Post() {
var notification models.Notification var notification models.Notification
@ -43,7 +43,7 @@ func (n *NotificationHandler) Post() {
} }
var username, action, repo, project string var username, action, repo, project string
for _, e := range notification.Events { for _, e := range notification.Events {
if e.Target.MediaType == MEDIA_TYPE_MANIFEST && strings.HasPrefix(e.Request.UserAgent, "docker") { if e.Target.MediaType == MediaTypeManifest && strings.HasPrefix(e.Request.UserAgent, "docker") {
username = e.Actor.Name username = e.Actor.Name
action = e.Action action = e.Action
repo = e.Target.Repository repo = e.Target.Repository

View File

@ -57,7 +57,8 @@ func FilterAccess(username string, authenticated bool, a *token.ResourceActions)
if a.Type == "registry" && a.Name == "catalog" { if a.Type == "registry" && a.Name == "catalog" {
return return
} else { }
//clear action list to assign to new acess element after perm check. //clear action list to assign to new acess element after perm check.
a.Actions = []string{} a.Actions = []string{}
if a.Type == "repository" { if a.Type == "repository" {
@ -96,7 +97,6 @@ func FilterAccess(username string, authenticated bool, a *token.ResourceActions)
} }
log.Printf("current access, type: %s, name:%s, actions:%v \n", a.Type, a.Name, a.Actions) log.Printf("current access, type: %s, name:%s, actions:%v \n", a.Type, a.Name, a.Actions)
} }
}
//For the UI process to call, so it won't establish a https connection from UI to proxy. //For the UI process to call, so it won't establish a https connection from UI to proxy.
func GenTokenForUI(username, service, scope string) (string, error) { func GenTokenForUI(username, service, scope string) (string, error) {

View File

@ -38,7 +38,7 @@ func init() {
} }
func RefreshCatalogCache() error { func RefreshCatalogCache() error {
result, err := RegistryApiGet(BuildRegistryUrl("_catalog"), "") result, err := RegistryAPIGet(BuildRegistryURL("_catalog"), "")
if err != nil { if err != nil {
return err return err
} }

View File

@ -24,7 +24,7 @@ import (
"strings" "strings"
) )
func BuildRegistryUrl(segments ...string) string { func BuildRegistryURL(segments ...string) string {
registryURL := os.Getenv("REGISTRY_URL") registryURL := os.Getenv("REGISTRY_URL")
if registryURL == "" { if registryURL == "" {
registryURL = "http://localhost:5000" registryURL = "http://localhost:5000"
@ -40,7 +40,7 @@ func BuildRegistryUrl(segments ...string) string {
return url return url
} }
func RegistryApiGet(url, username string) ([]byte, error) { func RegistryAPIGet(url, username string) ([]byte, error) {
response, err := http.Get(url) response, err := http.Get(url)
if err != nil { if err != nil {
return nil, err return nil, err