예제 #1
0
func (ra *RepositoryAPI) getUsername() (string, error) {
	// get username from session
	sessionUsername := ra.GetSession("username")
	if sessionUsername != nil {
		username, ok := sessionUsername.(string)
		if ok {
			return username, nil
		}
	}

	// if username does not exist in session, try to get userId from sessiion
	// and then get username from DB according to the userId
	sessionUserID := ra.GetSession("userId")
	if sessionUserID != nil {
		userID, ok := sessionUserID.(int)
		if ok {
			u := models.User{
				UserID: userID,
			}
			user, err := dao.GetUser(u)
			if err != nil {
				return "", err
			}

			return user.Username, nil
		}
	}

	return "", nil
}
예제 #2
0
// ResetPassword handles request from the reset page and reset password
func (cc *CommonController) ResetPassword() {

	resetUUID := cc.GetString("reset_uuid")
	if resetUUID == "" {
		cc.CustomAbort(http.StatusBadRequest, "Reset uuid is blank.")
	}

	queryUser := models.User{ResetUUID: resetUUID}
	user, err := dao.GetUser(queryUser)
	if err != nil {
		log.Errorf("Error occurred in GetUser: %v", err)
		cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
	}
	if user == nil {
		log.Error("User does not exist")
		cc.CustomAbort(http.StatusBadRequest, "User does not exist")
	}

	password := cc.GetString("password")

	if password != "" {
		user.Password = password
		err = dao.ResetUserPassword(*user)
		if err != nil {
			log.Errorf("Error occurred in ResetUserPassword: %v", err)
			cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
		}
	} else {
		cc.CustomAbort(http.StatusBadRequest, "password_is_required")
	}
}
예제 #3
0
파일: user.go 프로젝트: yaolingling/harbor
// Get ...
func (ua *UserAPI) Get() {
	if ua.userID == 0 { //list users
		if !ua.IsAdmin {
			log.Errorf("Current user, id: %d does not have admin role, can not list users", ua.currentUserID)
			ua.RenderError(http.StatusForbidden, "User does not have admin role")
			return
		}
		username := ua.GetString("username")
		userQuery := models.User{}
		if len(username) > 0 {
			userQuery.Username = "******" + username + "%"
		}
		userList, err := dao.ListUsers(userQuery)
		if err != nil {
			log.Errorf("Failed to get data from database, error: %v", err)
			ua.RenderError(http.StatusInternalServerError, "Failed to query from database")
			return
		}
		ua.Data["json"] = userList

	} else if ua.userID == ua.currentUserID || ua.IsAdmin {
		userQuery := models.User{UserID: ua.userID}
		u, err := dao.GetUser(userQuery)
		if err != nil {
			log.Errorf("Error occurred in GetUser, error: %v", err)
			ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
		}
		ua.Data["json"] = u
	} else {
		log.Errorf("Current user, id: %d does not have admin role, can not view other user's detail", ua.currentUserID)
		ua.RenderError(http.StatusForbidden, "User does not have admin role")
		return
	}
	ua.ServeJSON()
}
예제 #4
0
파일: main.go 프로젝트: yab/harbor
func updateInitPassword(userID int, password string) error {
	queryUser := models.User{UserID: userID}
	user, err := dao.GetUser(queryUser)
	if err != nil {
		return fmt.Errorf("Failed to get user, userID: %d %v", userID, err)
	}
	if user == nil {
		return fmt.Errorf("User id: %d does not exist.", userID)
	}
	if user.Salt == "" {
		salt, err := dao.GenerateRandomString()
		if err != nil {
			return fmt.Errorf("Failed to generate salt for encrypting password, %v", err)
		}

		user.Salt = salt
		user.Password = password
		err = dao.ChangeUserPassword(*user)
		if err != nil {
			return fmt.Errorf("Failed to update user encrypted password, userID: %d, err: %v", userID, err)
		}

		log.Infof("User id: %d updated its encypted password successfully.", userID)
	} else {
		log.Infof("User id: %d already has its encrypted password.", userID)
	}
	return nil
}
예제 #5
0
파일: base.go 프로젝트: yaolingling/harbor
// ValidateUser checks if the request triggered by a valid user
func (b *BaseAPI) ValidateUser() int {

	username, password, ok := b.Ctx.Request.BasicAuth()
	if ok {
		log.Infof("Requst with Basic Authentication header, username: %s", username)
		user, err := auth.Login(models.AuthModel{
			Principal: username,
			Password:  password,
		})
		if err != nil {
			log.Errorf("Error while trying to login, username: %s, error: %v", username, err)
			user = nil
		}
		if user != nil {
			return user.UserID
		}
	}
	sessionUserID := b.GetSession("userId")
	if sessionUserID == nil {
		log.Warning("No user id in session, canceling request")
		b.CustomAbort(http.StatusUnauthorized, "")
	}
	userID := sessionUserID.(int)
	u, err := dao.GetUser(models.User{UserID: userID})
	if err != nil {
		log.Errorf("Error occurred in GetUser, error: %v", err)
		b.CustomAbort(http.StatusInternalServerError, "Internal error.")
	}
	if u == nil {
		log.Warningf("User was deleted already, user id: %d, canceling request.", userID)
		b.CustomAbort(http.StatusUnauthorized, "")
	}
	return userID
}
예제 #6
0
파일: utils.go 프로젝트: yaoyu26/harbor
func checkUserExists(name string) int {
	u, err := dao.GetUser(models.User{Username: name})
	if err != nil {
		log.Errorf("Error occurred in GetUser, error: %v", err)
		return 0
	}
	if u != nil {
		return u.UserID
	}
	return 0
}
예제 #7
0
파일: user.go 프로젝트: yaolingling/harbor
// Prepare validates the URL and parms
func (ua *UserAPI) Prepare() {

	authMode := strings.ToLower(os.Getenv("AUTH_MODE"))
	if authMode == "" {
		authMode = "db_auth"
	}
	ua.AuthMode = authMode

	selfRegistration := strings.ToLower(os.Getenv("SELF_REGISTRATION"))
	if selfRegistration == "on" {
		ua.SelfRegistration = true
	}

	if ua.Ctx.Input.IsPost() {
		sessionUserID := ua.GetSession("userId")
		_, _, ok := ua.Ctx.Request.BasicAuth()
		if sessionUserID == nil && !ok {
			return
		}
	}

	ua.currentUserID = ua.ValidateUser()
	id := ua.Ctx.Input.Param(":id")
	if id == "current" {
		ua.userID = ua.currentUserID
	} else if len(id) > 0 {
		var err error
		ua.userID, err = strconv.Atoi(id)
		if err != nil {
			log.Errorf("Invalid user id, error: %v", err)
			ua.CustomAbort(http.StatusBadRequest, "Invalid user Id")
		}
		userQuery := models.User{UserID: ua.userID}
		u, err := dao.GetUser(userQuery)
		if err != nil {
			log.Errorf("Error occurred in GetUser, error: %v", err)
			ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
		}
		if u == nil {
			log.Errorf("User with Id: %d does not exist", ua.userID)
			ua.CustomAbort(http.StatusNotFound, "")
		}
	}

	var err error
	ua.IsAdmin, err = dao.IsAdminRole(ua.currentUserID)
	if err != nil {
		log.Errorf("Error occurred in IsAdminRole:%v", err)
		ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
	}

}
예제 #8
0
파일: user.go 프로젝트: yaolingling/harbor
// Put ...
func (ua *UserAPI) Put() {
	ldapAdminUser := (ua.AuthMode == "ldap_auth" && ua.userID == 1 && ua.userID == ua.currentUserID)

	if !(ua.AuthMode == "db_auth" || ldapAdminUser) {
		ua.CustomAbort(http.StatusForbidden, "")
	}
	if !ua.IsAdmin {
		if ua.userID != ua.currentUserID {
			log.Warning("Guests can only change their own account.")
			ua.CustomAbort(http.StatusForbidden, "Guests can only change their own account.")
		}
	}
	user := models.User{UserID: ua.userID}
	ua.DecodeJSONReq(&user)
	err := commonValidate(user)
	if err != nil {
		log.Warning("Bad request in change user profile: %v", err)
		ua.RenderError(http.StatusBadRequest, "change user profile error:"+err.Error())
		return
	}
	userQuery := models.User{UserID: ua.userID}
	u, err := dao.GetUser(userQuery)
	if err != nil {
		log.Errorf("Error occurred in GetUser, error: %v", err)
		ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
	}
	if u == nil {
		log.Errorf("User with Id: %d does not exist", ua.userID)
		ua.CustomAbort(http.StatusNotFound, "")
	}
	if u.Email != user.Email {
		emailExist, err := dao.UserExists(user, "email")
		if err != nil {
			log.Errorf("Error occurred in change user profile: %v", err)
			ua.CustomAbort(http.StatusInternalServerError, "Internal error.")
		}
		if emailExist {
			log.Warning("email has already been used!")
			ua.RenderError(http.StatusConflict, "email has already been used!")
			return
		}
	}
	if err := dao.ChangeUserProfile(user); err != nil {
		log.Errorf("Failed to update user profile, error: %v", err)
		ua.CustomAbort(http.StatusInternalServerError, err.Error())
	}
}
예제 #9
0
// Get renders user's navigation details header
func (ndc *NavigationDetailController) Get() {
	sessionUserID := ndc.GetSession("userId")
	var isAdmin int
	if sessionUserID != nil {
		userID := sessionUserID.(int)
		u, err := dao.GetUser(models.User{UserID: userID})
		if err != nil {
			log.Errorf("Error occurred in GetUser, error: %v", err)
			ndc.CustomAbort(http.StatusInternalServerError, "Internal error.")
		}
		if u == nil {
			log.Warningf("User was deleted already, user id: %d, canceling request.", userID)
			ndc.CustomAbort(http.StatusUnauthorized, "")
		}
		isAdmin = u.HasAdminRole
	}
	ndc.Data["IsAdmin"] = isAdmin
	ndc.TplName = "navigation-detail.htm"
	ndc.Render()
}
예제 #10
0
// Get checks if reset_uuid in the reset link is valid and render the result page for user to reset password.
func (rpc *ResetPasswordController) Get() {

	resetUUID := rpc.GetString("reset_uuid")
	if resetUUID == "" {
		log.Error("Reset uuid is blank.")
		rpc.Redirect("/", http.StatusFound)
		return
	}

	queryUser := models.User{ResetUUID: resetUUID}
	user, err := dao.GetUser(queryUser)
	if err != nil {
		log.Errorf("Error occurred in GetUser: %v", err)
		rpc.CustomAbort(http.StatusInternalServerError, "Internal error.")
	}

	if user != nil {
		rpc.Data["ResetUuid"] = user.ResetUUID
		rpc.Forward("page_title_reset_password", "reset-password.htm")
	} else {
		rpc.Redirect("/", http.StatusFound)
	}
}
예제 #11
0
// Get ...
func (pma *ProjectMemberAPI) Get() {
	pid := pma.project.ProjectID
	if !checkProjectPermission(pma.currentUserID, pid) {
		log.Warningf("Current user, user id: %d does not have permission for project, id: %d", pma.currentUserID, pid)
		pma.RenderError(http.StatusForbidden, "")
		return
	}
	if pma.memberID == 0 { //member id not set return list of the members
		username := pma.GetString("username")
		queryUser := models.User{Username: "******" + username + "%"}
		userList, err := dao.GetUserByProject(pid, queryUser)
		if err != nil {
			log.Errorf("Failed to query database for member list, error: %v", err)
			pma.RenderError(http.StatusInternalServerError, "Internal Server Error")
			return
		}
		pma.Data["json"] = userList
	} else { //return detail of a  member
		roleList, err := listRoles(pma.memberID, pid)
		if err != nil {
			log.Errorf("Error occurred in GetUserProjectRoles, error: %v", err)
			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 {
			log.Errorf("Error occurred in GetUser, error: %v", err)
			pma.CustomAbort(http.StatusInternalServerError, "Internal error.")
		}
		result["username"] = user.Username
		result["user_id"] = pma.memberID
		result["roles"] = roleList
		pma.Data["json"] = result
	}
	pma.ServeJSON()
}
예제 #12
0
//Get renders sign_in page
func (sic *SignInController) Get() {
	sessionUserID := sic.GetSession("userId")
	var hasLoggedIn bool
	var username string
	if sessionUserID != nil {
		hasLoggedIn = true
		userID := sessionUserID.(int)
		u, err := dao.GetUser(models.User{UserID: userID})
		if err != nil {
			log.Errorf("Error occurred in GetUser, error: %v", err)
			sic.CustomAbort(http.StatusInternalServerError, "Internal error.")
		}
		if u == nil {
			log.Warningf("User was deleted already, user id: %d, canceling request.", userID)
			sic.CustomAbort(http.StatusUnauthorized, "")
		}
		username = u.Username
	}
	sic.Data["AuthMode"] = sic.AuthMode
	sic.Data["Username"] = username
	sic.Data["HasLoggedIn"] = hasLoggedIn
	sic.TplName = "sign-in.htm"
	sic.Render()
}
예제 #13
0
// Get renders optional menu, Admin user has "Add User" menu
func (omc *OptionalMenuController) Get() {
	sessionUserID := omc.GetSession("userId")

	var hasLoggedIn bool
	var allowAddNew bool

	if sessionUserID != nil {
		hasLoggedIn = true
		userID := sessionUserID.(int)
		u, err := dao.GetUser(models.User{UserID: userID})
		if err != nil {
			log.Errorf("Error occurred in GetUser, error: %v", err)
			omc.CustomAbort(http.StatusInternalServerError, "Internal error.")
		}
		if u == nil {
			log.Warningf("User was deleted already, user id: %d, canceling request.", userID)
			omc.CustomAbort(http.StatusUnauthorized, "")
		}
		omc.Data["Username"] = u.Username

		isAdmin, err := dao.IsAdminRole(sessionUserID.(int))
		if err != nil {
			log.Errorf("Error occurred in IsAdminRole: %v", err)
			omc.CustomAbort(http.StatusInternalServerError, "")
		}

		if isAdmin && omc.AuthMode == "db_auth" {
			allowAddNew = true
		}
	}
	omc.Data["AddNew"] = allowAddNew
	omc.Data["HasLoggedIn"] = hasLoggedIn
	omc.TplName = "optional-menu.htm"
	omc.Render()

}
예제 #14
0
파일: ldap.go 프로젝트: CodingDance/harbor
// Authenticate checks user's credential agains LDAP based on basedn template and LDAP URL,
// if the check is successful a dummy record will be insert into DB, such that this user can
// be associated to other entities in the system.
func (l *Auth) Authenticate(m models.AuthModel) (*models.User, error) {

	ldapURL := os.Getenv("LDAP_URL")
	if ldapURL == "" {
		return nil, errors.New("Can not get any available LDAP_URL.")
	}
	log.Debug("ldapURL:", ldapURL)

	p := m.Principal
	for _, c := range metaChars {
		if strings.ContainsRune(p, c) {
			return nil, fmt.Errorf("the principal contains meta char: %q", c)
		}
	}

	ldap, err := openldap.Initialize(ldapURL)
	if err != nil {
		return nil, err
	}

	ldap.SetOption(openldap.LDAP_OPT_PROTOCOL_VERSION, openldap.LDAP_VERSION3)

	ldapBaseDn := os.Getenv("LDAP_BASE_DN")
	if ldapBaseDn == "" {
		return nil, errors.New("Can not get any available LDAP_BASE_DN.")
	}

	baseDn := fmt.Sprintf(ldapBaseDn, m.Principal)
	log.Debug("baseDn:", baseDn)

	err = ldap.Bind(baseDn, m.Password)
	if err != nil {
		return nil, err
	}
	defer ldap.Close()

	scope := openldap.LDAP_SCOPE_SUBTREE // LDAP_SCOPE_BASE, LDAP_SCOPE_ONELEVEL, LDAP_SCOPE_SUBTREE
	filter := "objectClass=*"
	attributes := []string{"mail"}

	result, err := ldap.SearchAll(baseDn, scope, filter, attributes)
	if err != nil {
		return nil, err
	}
	u := models.User{}
	if len(result.Entries()) == 1 {
		en := result.Entries()[0]
		for _, attr := range en.Attributes() {
			val := attr.Values()[0]
			if attr.Name() == "mail" {
				u.Email = val
			}
		}
	}

	u.Username = m.Principal
	log.Debug("username:"******",email:", u.Email)

	exist, err := dao.UserExists(u, "username")
	if err != nil {
		return nil, err
	}

	if exist {
		currentUser, err := dao.GetUser(u)
		if err != nil {
			return nil, err
		}
		u.UserID = currentUser.UserID
	} else {
		u.Realname = m.Principal
		u.Password = "******"
		u.Comment = "registered from LDAP."
		userID, err := dao.Register(u)
		if err != nil {
			return nil, err
		}
		u.UserID = int(userID)
	}
	return &u, nil
}