Пример #1
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")
	}
}
Пример #2
0
func CommonGetUserID() int {
	queryUser := &models.User{
		Username: TestUserName,
	}
	commonUser, _ := dao.GetUser(*queryUser)
	return commonUser.UserID
}
Пример #3
0
// 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
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 := utils.GenerateRandomString()

		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
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
}
Пример #6
0
func CommonDelUser() {
	queryUser := &models.User{
		Username: TestUserName,
	}
	commonUser, _ := dao.GetUser(*queryUser)
	_ = dao.DeleteUser(commonUser.UserID)

}
Пример #7
0
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
}
Пример #8
0
// 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.")
	}

}
Пример #9
0
func CommonAddProject() {

	queryUser := &models.User{
		Username: "******",
	}
	adminUser, _ := dao.GetUser(*queryUser)
	commonProject := &models.Project{
		Name:    TestProName,
		OwnerID: adminUser.UserID,
	}

	_, _ = dao.AddProject(*commonProject)

}
Пример #10
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

	var isAdminForLdap bool
	var allowSettingAccount 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

		if userID == 1 {
			isAdminForLdap = true
		}

		if omc.AuthMode == "db_auth" || isAdminForLdap {
			allowSettingAccount = true
		}

		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["SettingAccount"] = allowSettingAccount
	omc.Data["HasLoggedIn"] = hasLoggedIn
	omc.TplName = "optional-menu.htm"
	omc.Render()

}
Пример #11
0
// 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.Warningf("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())
	}
}
Пример #12
0
// ValidateUser checks if the request triggered by a valid user
func (b *BaseAPI) ValidateUser() int {
	userID, needsCheck, ok := b.GetUserIDForRequest()
	if !ok {
		log.Warning("No user id in session, canceling request")
		b.CustomAbort(http.StatusUnauthorized, "")
	}
	if needsCheck {
		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
}
Пример #13
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.")
		}

		if len(roleList) == 0 {
			pma.CustomAbort(http.StatusNotFound, fmt.Sprintf("user %d is not a member of the project", pma.memberID))
		}

		//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()
}
Пример #14
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()
}
Пример #15
0
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 == "" {
		user.Salt = utils.GenerateRandomString()
		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)
		}

	} else {
	}
	return nil
}
Пример #16
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)
	}
}
Пример #17
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()
}
Пример #18
0
// Authenticate checks user's credential against LDAP based on basedn template and LDAP URL,
// if the check is successful a dummy record will be inserted 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) {

	p := m.Principal
	for _, c := range metaChars {
		if strings.ContainsRune(p, c) {
			return nil, fmt.Errorf("the principal contains meta char: %q", c)
		}
	}
	ldapURL := config.LDAP().URL
	if ldapURL == "" {
		return nil, errors.New("can not get any available LDAP_URL")
	}
	log.Debug("ldapURL:", ldapURL)
	ldap, err := openldap.Initialize(ldapURL)
	if err != nil {
		return nil, err
	}
	ldap.SetOption(openldap.LDAP_OPT_PROTOCOL_VERSION, openldap.LDAP_VERSION3)

	ldapBaseDn := config.LDAP().BaseDn
	if ldapBaseDn == "" {
		return nil, errors.New("can not get any available LDAP_BASE_DN")
	}
	log.Debug("baseDn:", ldapBaseDn)

	ldapSearchDn := config.LDAP().SearchDn
	if ldapSearchDn != "" {
		log.Debug("Search DN: ", ldapSearchDn)
		ldapSearchPwd := config.LDAP().SearchPwd
		err = ldap.Bind(ldapSearchDn, ldapSearchPwd)
		if err != nil {
			log.Debug("Bind search dn error", err)
			return nil, err
		}
	}

	attrName := config.LDAP().UID
	filter := config.LDAP().Filter
	if filter != "" {
		filter = "(&" + filter + "(" + attrName + "=" + m.Principal + "))"
	} else {
		filter = "(" + attrName + "=" + m.Principal + ")"
	}
	log.Debug("one or more filter", filter)

	ldapScope := config.LDAP().Scope
	var scope int
	if ldapScope == "1" {
		scope = openldap.LDAP_SCOPE_BASE
	} else if ldapScope == "2" {
		scope = openldap.LDAP_SCOPE_ONELEVEL
	} else {
		scope = openldap.LDAP_SCOPE_SUBTREE
	}
	attributes := []string{"uid", "cn", "mail", "email"}
	result, err := ldap.SearchAll(ldapBaseDn, scope, filter, attributes)
	if err != nil {
		return nil, err
	}
	if len(result.Entries()) == 0 {
		log.Warningf("Not found an entry.")
		return nil, nil
	} else if len(result.Entries()) != 1 {
		log.Warningf("Found more than one entry.")
		return nil, nil
	}
	en := result.Entries()[0]
	bindDN := en.Dn()
	log.Debug("found entry:", en)
	err = ldap.Bind(bindDN, m.Password)
	if err != nil {
		log.Debug("Bind user error", err)
		return nil, err
	}
	defer ldap.Close()

	u := models.User{}
	for _, attr := range en.Attributes() {
		val := attr.Values()[0]
		switch attr.Name() {
		case "uid":
			u.Realname = val
		case "cn":
			u.Realname = val
		case "mail":
			u.Email = val
		case "email":
			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."
		if u.Email == "" {
			u.Email = u.Username + "@placeholder.com"
		}
		userID, err := dao.Register(u)
		if err != nil {
			return nil, err
		}
		u.UserID = int(userID)
	}
	return &u, nil
}