func loginHandler(w http.ResponseWriter, r *http.Request) {
	var (
		username  string
		password  string
		queryx    string
		get_login string
	)

	username = r.FormValue("username")
	password = r.FormValue("password")

	RedirectDN := r.FormValue("RPR")

	if len(RedirectDN) < 1 {
		RedirectDN = "/"
	} else {
		RedirectDN = strings.Replace(RedirectDN, "'", "", -1)
	}

	if r.FormValue("go") == "unlogin" {
		RemoveUserSession(r)
		http.Redirect(w, r, RedirectDN, http.StatusMovedPermanently)
	}

	remIPClient := getIPAddress(r)

	SABModules.Log_ON(&rconf)
	defer SABModules.Log_OFF()

	if len(username) < 2 || len(password) < 2 {

		log.Printf("%s AAA Get login form...", remIPClient)

		t, err := template.ParseFiles("templates/header.html")
		if err != nil {
			fmt.Fprintf(w, err.Error())
			log.Println(err.Error())
			return
		}

		t.ExecuteTemplate(w, "header", template.FuncMap{"Pagetitle": rconf.WLB_HTML_Title, "FRColor": "#FF0000", "BGColor": "#FFEEEE"})

		t, err = template.ParseFiles("templates/search.html")
		if err != nil {
			fmt.Fprintf(w, err.Error())
			log.Println(err.Error())
			return
		}

		t.ExecuteTemplate(w, "search", template.FuncMap{"GoHome": "Yes", "LineColor": "#FFDDDD"})

		t, err = template.ParseFiles("templates/login.html")
		if err != nil {
			fmt.Fprintf(w, err.Error())
			log.Println(err.Error())
			return
		}

		t.ExecuteTemplate(w, "login", template.FuncMap{"RedirectDN": RedirectDN})

		t, err = template.ParseFiles("templates/footer.html")
		if err != nil {
			fmt.Fprintf(w, err.Error())
			log.Println(err.Error())
			return
		}

		t.ExecuteTemplate(w, "footer", template.FuncMap{"WebBookVersion": pVersion, "xMailBT": rconf.WLB_MailBT, "LineColor": "#FFDDDD"})

	} else {
		/*		dbpg, err := sql.Open("postgres", rconf.PG_DSN)
				if err != nil {
					log.Printf("PG::Open() error: %v\n", err)
					return
				}
				defer dbpg.Close()
		*/

		dbpg, err := sql.Open("postgres", rconf.PG_DSN)
		if err != nil {
			log.Fatalf("PG_INIT::Open() error: %v\n", err)
		}

		defer dbpg.Close()

		queryx = fmt.Sprintf("select distinct login from aaa_logins where login='******' and password=md5('%s:%s:%s') limit 1;", username, username, rconf.SABRealm, password)
		//fmt.Printf("%s\n", queryx)
		rows, err := dbpg.Query(queryx)
		if err != nil {
			log.Printf("PG::Query() Check login and password: %v\n", err)
			return
		}

		rows.Next()
		rows.Scan(&get_login)

		if get_login == username {
			userID := StoreUserSession(username, w)
			if userID == "error" {
				return
			}

			log.Printf("%s AAA Login enter with username %s (%s)\n", remIPClient, username, userID)

			http.Redirect(w, r, RedirectDN, http.StatusMovedPermanently)

		} else {
			log.Printf("%s AAA Login ERROR with username %s\n", remIPClient, username)
			http.Redirect(w, r, "/login", http.StatusMovedPermanently)
		}
	}

}
func main() {

	const (
		pName = string("SABook AsteriskCIDUpdater")
		pVer  = string("3 2015.09.10.21.10")
	)

	var (
		def_config_file = string("./AsteriskCIDUpdater.json")             // Default configuration file
		def_log_file    = string("/var/log/ABook/AsteriskCIDUpdater.log") // Default log file
		def_daemon_mode = string("NO")                                    // Default start in foreground

		sqlite_key   string
		sqlite_value string

		pg_name  string
		pg_phone string

		pg_array [100000][3]string
		sq_array [100000][3]string

		pg_array_len = int(0)
		sq_array_len = int(0)

		ckl1       = int(0)
		ckl2       = int(0)
		ckl_status = int(0)

		ast_cmd string

		rconf SABModules.Config_STR

		sql_mode = int(0)

		query string
	)

	fmt.Printf("\n\t%s V%s\n\n", pName, pVer)

	rconf.LOG_File = def_log_file

	def_config_file, def_daemon_mode = SABModules.ParseCommandLine(def_config_file, def_daemon_mode)

	//	log.Printf("%s %s %s", def_config_file, def_daemon_mode, os.Args[0])

	SABModules.ReadConfigFile(def_config_file, &rconf)

	sqlite_select := fmt.Sprintf("SELECT key, value FROM astdb where key like '%%%s%%';", rconf.AST_CID_Group)
	pg_select := fmt.Sprintf("select x.cid_name, y.phone from ldapx_persons x, ldapx_phones y, (select a.phone, count(a.phone) as phone_count from ldapx_phones as a, ldapx_persons as b where a.pers_id=b.uid and b.contract=0 and a.pass=2 and b.lang=1 group by a.phone order by a.phone) as subq where x.uid=y.pers_id and y.pass=2 and x.lang=1 and subq.phone=y.phone and subq.phone_count<2 and y.phone like '%s%%' and x.contract=0 group by x.cid_name, y.phone order by y.phone;", rconf.AST_Num_Start)

	SABModules.Pid_Check(&rconf)
	SABModules.Pid_ON(&rconf)

	SABModules.Log_ON(&rconf)

	log.Printf(".")
	log.Printf("..")
	log.Printf("...")
	log.Printf("-> %s V%s", pName, pVer)
	log.Printf("--> Go!")

	db, err := sql.Open("sqlite3", rconf.AST_SQLite_DB)
	if err != nil {
		log.Printf("SQLite3::Open() error: %v\n", err)
		return
	}

	defer db.Close()

	dbpg, err := sql.Open("postgres", rconf.PG_DSN)
	if err != nil {
		log.Printf("PG::Open() error: %v\n", err)
		return
	}

	defer dbpg.Close()

	dbast, err := net.Dial("tcp", fmt.Sprintf("%s:%d", rconf.AST_ARI_Host, rconf.AST_ARI_Port))
	if err != nil {
		log.Printf(".")
		log.Printf("Asterisk ARI::Dial() error: %v", err)
		log.Printf("\tWorking in SQL SQLite mode!")
		log.Printf(".")
		sql_mode = 1
	}

	if sql_mode == 0 {
		defer dbast.Close()
	}

	ast_gami := gami.NewAsterisk(&dbast, nil)
	ast_get := make(chan gami.Message, 10000)

	if sql_mode == 0 {
		err = ast_gami.Login(rconf.AST_ARI_User, rconf.AST_ARI_Pass)
		if err != nil {
			log.Printf("Asterisk ARI::Login() error: %v\n", err)
			return
		}
	}

	rows, err := db.Query(sqlite_select)
	if err != nil {
		log.Printf("SQLite3::Query() error: %v\n", err)
		return
	}

	for rows.Next() {

		err = rows.Scan(&sqlite_key, &sqlite_value)
		if err != nil {
			log.Printf("rows.Scan error: %v\n", err)
			return
		}

		sq_array[sq_array_len][0] = sqlite_key
		sq_array[sq_array_len][1] = sqlite_value
		sq_array[sq_array_len][2] = SABModules.PhoneMutation(sqlite_key)
		sq_array_len++

	}

	rows, err = dbpg.Query(pg_select)
	if err != nil {
		log.Printf("PG::Query() error: %v\n", err)
		return
	}

	pg_array_len = 0
	for rows.Next() {

		err = rows.Scan(&pg_name, &pg_phone)
		if err != nil {
			log.Printf("rows.Scan error: %v\n", err)
			return
		}

		pg_array[pg_array_len][0] = fmt.Sprintf("/%s/%s", rconf.AST_CID_Group, pg_phone)
		pg_array[pg_array_len][1] = pg_name
		pg_array[pg_array_len][2] = SABModules.PhoneMutation(pg_phone)
		pg_array_len++

	}

	for ckl1 = 0; ckl1 < sq_array_len; ckl1++ {
		ckl_status = 0
		for ckl2 = 0; ckl2 < pg_array_len; ckl2++ {
			if sq_array[ckl1][0] == pg_array[ckl2][0] && sq_array[ckl1][1] == pg_array[ckl2][1] {
				ckl_status = 1
				break
			}
		}
		if ckl_status == 0 {
			if sql_mode == 0 {
				ast_cmd = fmt.Sprintf("database del %s %s", rconf.AST_CID_Group, sq_array[ckl1][2])
				log.Printf("\t- %s\n", ast_cmd)

				ast_cb := func(m gami.Message) {
					ast_get <- m
				}

				err = ast_gami.Command(ast_cmd, &ast_cb)
				if err != nil {
					log.Printf("Asterisk ARI::Command() error: %v\n", err)
					return
				}

				for x1, x2 := range <-ast_get {
					if x1 == "ActionID" || x1 == "CmdData" || x1 == "Usage" {
						log.Printf("\t\t\t%s\n", x2)
					}
				}
			} else {
				query = fmt.Sprintf("delete from astdb where key='%s';", sq_array[ckl1][0])
				log.Printf("\t- %s\n", query)
				_, err := db.Exec(query)
				if err != nil {
					log.Printf("SQLite3::Query() DEL error: %v\n", err)
					return
				}
			}
		}
	}

	for ckl1 = 0; ckl1 < pg_array_len; ckl1++ {
		ckl_status = 0
		for ckl2 = 0; ckl2 < sq_array_len; ckl2++ {
			if pg_array[ckl1][0] == sq_array[ckl2][0] && pg_array[ckl1][1] == sq_array[ckl2][1] {
				ckl_status = 1
				break
			}
		}
		if ckl_status == 0 {

			if sql_mode == 0 {
				ast_cmd = fmt.Sprintf("database del %s %s", rconf.AST_CID_Group, pg_array[ckl1][2])
				log.Printf("\t- %s\n", ast_cmd)

				ast_cb := func(m gami.Message) {
					ast_get <- m
				}

				err = ast_gami.Command(ast_cmd, &ast_cb)
				if err != nil {
					log.Printf("Asterisk ARI::Command() error: %v\n", err)
					return
				}

				for x1, x2 := range <-ast_get {
					if x1 == "ActionID" || x1 == "CmdData" || x1 == "Usage" {
						log.Printf("\t\t\t%s\n", x2)
					}
				}

				ast_cmd = fmt.Sprintf("database put %s %s \"%s\"", rconf.AST_CID_Group, pg_array[ckl1][2], pg_array[ckl1][1])
				log.Printf("\t+ %s\n", ast_cmd)

				ast_cb = func(m gami.Message) {
					ast_get <- m
				}

				err = ast_gami.Command(ast_cmd, &ast_cb)
				if err != nil {
					log.Printf("Asterisk ARI::Command() error: %v\n", err)
					return
				}

				for x1, x2 := range <-ast_get {
					if x1 == "ActionID" || x1 == "CmdData" || x1 == "Usage" {
						log.Printf("\t\t\t%s\n", x2)
					}
				}
			} else {
				query = fmt.Sprintf("delete from astdb where key='%s';", pg_array[ckl1][0])
				log.Printf("\t- %s\n", query)
				_, err := db.Exec(query)
				if err != nil {
					log.Printf("SQLite3::Query() DEL error: %v\n", err)
					return
				}

				query = fmt.Sprintf("insert into astdb (key,value) values ('%s','%s');", pg_array[ckl1][0], pg_array[ckl1][1])
				log.Printf("\t+ %s\n", query)
				_, err = db.Exec(query)
				if err != nil {
					log.Printf("SQLite3::Query() INS error: %v\n", err)
					return
				}
			}
		}
	}

	log.Printf("...")
	log.Printf("..")
	log.Printf(".")

	SABModules.Log_OFF()

	SABModules.Pid_OFF(&rconf)

}
Example #3
0
func main() {

	const (
		pName = string("SABook Exporter Daemon")
		pVer  = string("4 2015.10.25.22.00")

		pg_MultiInsert = int(50)
	)

	var (
		def_config_file = string("./Exporter.json")             // Default configuration file
		def_log_file    = string("/var/log/ABook/Exporter.log") // Default log file
		def_daemon_mode = string("NO")                          // Default start in foreground
		my_error        int
		st_MSSQL_to_PG  = int(0)
		st_LDAP_to_PG   = int(0)
		st_Oracle_to_PG = int(0)
		st_LDAP_UP      = int(0)
		st_AD_UP        = int(0)
		st_AD_to_PG     = int(0)
		st_DB_clean     = int(0)
		sleep_counter   = int(0)
		rconf           SABModules.Config_STR
	)

	fmt.Printf("\n\t%s V%s\n\n", pName, pVer)

	rconf.LOG_File = def_log_file

	def_config_file, def_daemon_mode = SABModules.ParseCommandLine(def_config_file, def_daemon_mode)

	//	log.Printf("%s %s %s", def_config_file, def_daemon_mode, os.Args[0])

	SABModules.ReadConfigFile(def_config_file, &rconf)

	SABModules.Pid_Check(&rconf)

	if def_daemon_mode == "YES" {
		if err := exec.Command(os.Args[0], fmt.Sprintf("-daemon=GO -config=%s &", def_config_file)).Start(); err != nil {
			log.Fatalf("Fork daemon error: %v", err)
		} else {
			log.Printf("Forked!")
			os.Exit(0)
		}
	}

	SABModules.Log_ON(&rconf)
	SABModules.Log_OFF()

	SABModules.Pid_ON(&rconf)

	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt, os.Kill, syscall.SIGTERM)
	go func() {
		signalType := <-ch
		signal.Stop(ch)

		SABModules.Log_ON(&rconf)

		log.Printf(".")
		log.Printf("..")
		log.Printf("...")
		log.Printf("Exit command received. Exiting...")
		log.Println("Signal type: ", signalType)
		log.Printf("Bye...")
		log.Printf("...")
		log.Printf("..")
		log.Printf(".")

		SABModules.Log_OFF()

		SABModules.Pid_OFF(&rconf)

		os.Exit(0)
	}()

	for {

		SABModules.Log_ON(&rconf)

		if sleep_counter == 0 {
			log.Printf("-> %s V%s", pName, pVer)
			log.Printf("--> Go!")
		} else {
			log.Printf("--> WakeUP!")
		}

		//KILL
		//SABFunctions.AD_to_PG(&rconf, pg_MultiInsert)
		//SABFunctions.LDAP_Make(&rconf)
		//SABFunctions.AD_Analyze(&rconf)
		//KILL

		//os.Exit(0)

		if st_MSSQL_to_PG == 0 {
			if my_error = SABFunctions.MSSQL_to_PG(&rconf, pg_MultiInsert); my_error != 94 {
				log.Printf("MSSQL_to_PG() error:%v\n", my_error)
			} else {
				st_MSSQL_to_PG = 1
			}
			log.Printf("-")
		}

		if st_LDAP_to_PG == 0 {
			if my_error = SABFunctions.LDAP_to_PG(&rconf, pg_MultiInsert); my_error != 94 {
				log.Printf("LDAP_to_PG() my_error: %v\n", my_error)
			} else {
				st_LDAP_to_PG = 1
			}
			log.Printf("-")
		}

		if st_Oracle_to_PG == 0 {
			if my_error = SABFunctions.Oracle_to_PG(&rconf, pg_MultiInsert); my_error != 94 {
				log.Printf("Oracle_to_PG() mode 1 my_error:%v\n", my_error)
			} else {
				st_Oracle_to_PG = 1
			}
			log.Printf("-")
		}

		if st_AD_to_PG == 0 {
			if my_error = SABFunctions.AD_to_PG(&rconf, pg_MultiInsert); my_error != 94 {
				log.Printf("AD_to_PG() my_error: %v\n", my_error)
			} else {
				st_AD_to_PG = 1
			}
			log.Printf("-")
		}

		if st_LDAP_to_PG > 0 && st_Oracle_to_PG > 0 && st_MSSQL_to_PG > 0 && st_AD_to_PG > 0 {
			if st_DB_clean == 0 {
				if my_error = SABFunctions.RemoveNoChildrenCache(&rconf); my_error != 94 {
					log.Printf("RemoveNoChildrenCache error: %v\n", my_error)
				} else {
					st_DB_clean = 1
				}
			}
			if st_DB_clean > 0 {
				if st_LDAP_UP == 0 {
					if my_error = SABFunctions.LDAP_Make(&rconf); my_error != 94 {
						log.Printf("LDAP_Make error: %v\n", my_error)
					} else {
						st_LDAP_UP = 1
					}
				}
				if st_AD_UP == 0 {
					if my_error = SABFunctions.AD_Analyze(&rconf); my_error != 94 {
						log.Printf("AD Analyze error: %v\n", my_error)
					} else {
						st_AD_UP = 1
					}
				}
			}
		}

		sleep_counter++

		if sleep_counter > rconf.Sleep_cycles-1 {

			st_LDAP_to_PG = 0
			st_Oracle_to_PG = 0
			st_MSSQL_to_PG = 0
			st_AD_to_PG = 0

			st_DB_clean = 0

			st_LDAP_UP = 0
			st_AD_UP = 0

			sleep_counter = 0

		}

		log.Printf("----- Cycle %d of %d ----- Sleep for %d sec...", sleep_counter, rconf.Sleep_cycles, rconf.Sleep_Time)

		SABModules.Log_OFF()

		time.Sleep(time.Duration(rconf.Sleep_Time) * time.Second)

	}

}
Example #4
0
func main() {

	pVersion = fmt.Sprintf("%s V%s", pName, pVer)

	fmt.Printf("\n\t%s\n\n", pVersion)

	rconf.LOG_File = def_log_file

	def_config_file, def_daemon_mode = SABModules.ParseCommandLine(def_config_file, def_daemon_mode)

	SABModules.ReadConfigFile(def_config_file, &rconf)

	SABModules.Pid_Check(&rconf)
	SABModules.Pid_ON(&rconf)

	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt, os.Kill, syscall.SIGTERM)
	go func() {
		signalType := <-ch
		signal.Stop(ch)

		SABModules.Log_ON(&rconf)

		log.Printf(".")
		log.Printf("..")
		log.Printf("...")
		log.Printf("Exit command received. Exiting...")
		log.Println("Signal type: ", signalType)
		log.Printf("Bye...")
		log.Printf("...")
		log.Printf("..")
		log.Printf(".")

		SABModules.Log_OFF()

		SABModules.Pid_OFF(&rconf)

		os.Exit(0)
	}()

	/*	err := httpscerts.Check("cert.pem", "key.pem")
		if err != nil {
			err = httpscerts.Generate("cert.pem", "key.pem", rconf.WLB_Listen_IP)
			if err != nil {
				log.Println("Error: Couldn't create https certs.")
				os.Exit(1)
			}
		}*/
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./css/"))))
	http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("./images/"))))
	http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./js/"))))
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/modify", modifyHandler)
	http.HandleFunc("/login", loginHandler)
	http.HandleFunc("/GoOrg", indexHandler)
	http.HandleFunc("/DavDN", davDNHandler)
	//	fmt.Printf("1 %v\n", rconf)
	//	fmt.Printf("2 %s / %s\n", rconf.WLB_Listen_IP, fmt.Sprintf("%s",rconf.WLB_Listen_PORT))
	//	fmt.Printf("3\n")
	//	fmt.Printf("4\n")

	//	go http.ListenAndServeTLS(rconf.WLB_Listen_IP+":443", "cert.pem", "key.pem", nil)
	//	http.ListenAndServe(rconf.WLB_Listen_IP+":80", http.HandlerFunc(redirectToHttps))
	//	fmt.Printf("5 %s / %s\n", rconf.WLB_Listen_IP, fmt.Sprintf("%s",rconf.WLB_Listen_PORT))

	SABModules.Log_ON(&rconf)

	log.Printf("->")
	log.Printf("--> %s", pVersion)
	log.Printf("---> I'm Ready...")
	log.Printf(" _")

	pgInit()

	SABModules.Log_OFF()

	go func() {
		for {
			SABModules.Log_ON(&rconf)
			log.Printf("Session cleaner ***** Remove old sessions...")

			dbpg, err := sql.Open("postgres", rconf.PG_DSN)
			if err != nil {
				log.Fatalf("PG_INIT::Open() error: %v\n", err)
			}

			queryx := fmt.Sprintf("delete from wb_auth_session where exptime<%v;", int64(time.Now().Unix()-int64(rconf.WLB_SessTimeOut*60+30)))
			_, err = dbpg.Query(queryx)
			if err != nil {
				log.Printf("%s\n", queryx)
				log.Printf("PG::Query() Get User Name for UID: %v\n", err)
				return
			}

			dbpg.Close()

			log.Printf("Session cleaner ***** Sleep for %d seconds...", rconf.Sleep_Time)
			SABModules.Log_OFF()
			time.Sleep(time.Duration(rconf.Sleep_Time) * time.Second)

		}
	}()

	http.ListenAndServe(rconf.WLB_Listen_IP+":"+fmt.Sprintf("%d", rconf.WLB_Listen_PORT), nil)
}
Example #5
0
func indexHandler(w http.ResponseWriter, r *http.Request) {
	var (
		xSearchPplMode = int(0)
		xSearch        string
		xMessage       string

		dn          string
		dn_back     string
		dn_back_tmp []string

		go_home_button string

		ldap_Search string

		ldapSearchMode = int(1)

		ckl1 int

		ldap_Attr []string

		xGetDN  [1000]string
		xGetCkl int

		l   *ldap.Conn
		err error

		xFRColor     = string("#FFFFFF")
		xBGColor     = string("#FFFFFF")
		LUserName    = string("")
		setAdminMode = string("")
	)

	username, userperm := CheckUserSession(r, w)

	//fmt.Printf("%s / %d\n", username, userperm)

	switch userperm {
	case roleAdmin:
		xFRColor = "#FF0000"
		xBGColor = "#FFFFFF"
		LUserName = username
		setAdminMode = "Yes"
	case roleUser:
		xFRColor = "#0000FF"
		xBGColor = "#FFFFFF"
		LUserName = username
	default:
		xFRColor = "#FFFFFF"
		xBGColor = "#FFFFFF"
		LUserName = ""
	}

	ldap_Attr = make([]string, len(rconf.WLB_LDAP_ATTR))

	for ckl1 := 0; ckl1 < len(rconf.WLB_LDAP_ATTR); ckl1++ {
		ldap_Attr[ckl1] = rconf.WLB_LDAP_ATTR[ckl1][0]
	}

	SABModules.Log_ON(&rconf)
	defer SABModules.Log_OFF()

	get_dn := r.FormValue("dn")
	get_cn := r.FormValue("cn")
	get_fn := r.FormValue("FirstName")
	get_ln := r.FormValue("LastName")
	searchMode := r.FormValue("SearchMode")

	remIPClient := getIPAddress(r)
	//	log.Printf("DN: %s --- CN: %s", get_dn, get_cn)

	if get_dn == "" {
		dn = rconf.LDAP_URL[ldap_count][3]
	} else {
		dn = get_dn
	}

	if len(dn) < len(rconf.LDAP_URL[ldap_count][3]) {
		dn = rconf.LDAP_URL[ldap_count][3]
	}

	log.Printf("->")
	log.Printf("--> %s", pVersion)
	log.Printf("->")
	ucurl, _ := strconv.Unquote(r.RequestURI)
	log.Println(remIPClient + " --> http://" + r.Host + ucurl)
	log.Printf("%s ++> DN: %s / CN: %s / Mode: %d / Def.DN: %s", remIPClient, dn, ldap_Search, ldapSearchMode, rconf.LDAP_URL[ldap_count][3])

	if get_cn == "" && get_ln == "" && get_fn == "" {
		ldap_Search = rconf.LDAP_URL[ldap_count][4]
	} else {
		log.Printf("%s ++> SQL Search: %s/%s/%s\n", remIPClient, get_cn, get_fn, get_ln)
		dbpg, err := sql.Open("postgres", rconf.PG_DSN)
		if err != nil {
			log.Fatalf("PG_INIT::Open() error: %v\n", err)
		}

		defer dbpg.Close()

		queryx := "select x.dn from ldap_entries as x, ldapx_persons as y where x.uid=y.uid"
		if len(get_cn) > 2 {
			queryx = fmt.Sprintf("%s and lower(fullname) like lower('%%%s%%')", queryx, strings.ToLower(get_cn))
		}
		if len(get_ln) > 2 {
			queryx = fmt.Sprintf("%s and lower(surname) like lower('%s%%')", queryx, strings.ToLower(get_ln))
		}
		if len(get_fn) > 2 {
			queryx = fmt.Sprintf("%s and lower(name) like lower('%s%%')", queryx, strings.ToLower(get_fn))
		}
		if len(get_cn) <= 2 && len(get_ln) <= 2 && len(get_fn) <= 2 {
			queryx = fmt.Sprintf("%s and 2=3;", queryx)
		} else {
			queryx = fmt.Sprintf("%s;", queryx)
		}
		//		log.Printf("Search QUERY: %s\n", queryx)
		rows, err := dbpg.Query(queryx)
		if err != nil {
			fmt.Printf("SQL Error: %s\n", queryx)
			log.Printf("PG::Query() Check LDAP tables error: %v\n", err)
			return
		}
		xGetCkl = 0
		for rows.Next() {
			rows.Scan(&xGetDN[xGetCkl])
			//fmt.Println("XXX:", xGetDN[xGetCkl], dn)
			if strings.Contains(strings.ToLower(xGetDN[xGetCkl]), strings.ToLower(dn)) || searchMode == "Full" {
				log.Printf("%s <-- SQL Found: %s\n", remIPClient, xGetDN[xGetCkl])
				xGetCkl++
				if xGetCkl > userLimit {
					xMessage = fmt.Sprintf("Количество персон по вашему запросу превысило %d! Пожалуйста, задайте критерии более конкретно!", userLimit)
					break
				}
			}
		}
		xSearchPplMode = 1
		ldapSearchMode = 2
	}

	if strings.ToLower(dn) != strings.ToLower(rconf.LDAP_URL[ldap_count][3]) || xSearchPplMode == 1 {
		go_home_button = "+"
	}
	if ldapSearchMode != 2 {
		xSearch = "+"
	}

	if strings.ToLower(dn) != strings.ToLower(rconf.LDAP_URL[ldap_count][3]) {
		if ldapSearchMode == 1 && xSearchPplMode == 0 {
			dn_back_tmp = strings.Split(dn, ",")
			for ckl1 = 1; ckl1 < len(dn_back_tmp); ckl1++ {
				if ckl1 == 1 {
					dn_back = dn_back_tmp[ckl1]
				} else {
					dn_back += fmt.Sprintf(",%s", dn_back_tmp[ckl1])
				}
			}
		}
	}

	//	log.Printf("%s ... Initialize LDAP connector...", remIPClient)

	if initLDAPConnector() == "error" {
		return
	}

	l, err = ldap.Dial("tcp", rconf.LDAP_URL[ldap_count][0])
	if err != nil {
		fmt.Fprintf(w, err.Error())
		log.Printf("LDAP::Initialize() error: %v\n", err)
		return
	}

	//		l.Debug = true
	defer l.Close()

	log.Printf("%s =!= Connected to server %d of %d: %s", remIPClient, ldap_count+1, len(rconf.LDAP_URL), rconf.LDAP_URL[ldap_count][0])

	err = l.Bind(rconf.LDAP_URL[ldap_count][1], rconf.LDAP_URL[ldap_count][2])
	if err != nil {
		fmt.Fprintf(w, err.Error())
		log.Printf("LDAP::Bind() error: %v\n", err)
		return
	}

	t, err := template.ParseFiles("templates/header.html")
	if err != nil {
		fmt.Fprintf(w, err.Error())
		log.Println(err.Error())
		return
	}

	t.ExecuteTemplate(w, "header", template.FuncMap{"Pagetitle": rconf.WLB_HTML_Title, "FRColor": xFRColor, "BGColor": xBGColor})

	t, err = template.ParseFiles("templates/search.html")
	if err != nil {
		fmt.Fprintf(w, err.Error())
		log.Println(err.Error())
		return
	}

	t.ExecuteTemplate(w, "search", template.FuncMap{"GoHome": go_home_button, "PrevDN": dn_back, "DN": dn, "xSearch": xSearch, "xMessage": xMessage, "LineColor": "#EEEEEE", "LUserName": LUserName, "LoginShow": "Yes", "RedirectDN": r.RequestURI})

	t, err = template.ParseFiles("templates/index.html")
	if err != nil {
		fmt.Fprintf(w, err.Error())
		log.Println(err.Error())
		return
	}

	if xSearchPplMode == 0 {

		search := ldap.NewSearchRequest(dn, ldapSearchMode, ldap.NeverDerefAliases, 0, 0, false, ldap_Search, ldap_Attr, nil)

		//	log.Printf("Search: %v\n%v\n%v\n%v\n%v\n%v\n", search, dn, ldapSearchMode, ldap.NeverDerefAliases, ldap_Search, ldap_Attr)

		sr, err := l.Search(search)
		if err != nil {
			fmt.Fprintf(w, err.Error())
			log.Printf("LDAP::Search() error: %v\n", err)
			return
		}

		//	fmt.Printf("\n\nSearch: %v", search)

		log.Printf("%s ++> search: %s // found: %d\n", remIPClient, search.Filter, len(sr.Entries))

		if len(sr.Entries) > 0 {
			dnList := make(map[string]tList, len(sr.Entries))
			for _, entry := range sr.Entries {
				fType := ""
				fField := make(map[string]string, len(rconf.WLB_LDAP_ATTR))
				for _, attr := range entry.Attributes {
					for ckl1 := 0; ckl1 < len(rconf.WLB_LDAP_ATTR); ckl1++ {
						if attr.Name == rconf.WLB_LDAP_ATTR[ckl1][0] {
							fField[rconf.WLB_LDAP_ATTR[ckl1][1]] = fmt.Sprintf("%s", strings.Join(attr.Values, ","))
							//						fmt.Printf("Name: %s==%s --> %s = %s\n", attr.Name, rconf.WLB_LDAP_ATTR[ckl1][0], rconf.WLB_LDAP_ATTR[ckl1][1], fField[rconf.WLB_LDAP_ATTR[ckl1][1]])
							if rconf.WLB_LDAP_ATTR[ckl1][1] == "ORGName" {
								fType = "Org"
							}
							if rconf.WLB_LDAP_ATTR[ckl1][1] == "USERName" {
								fType = "User"
							}
						}
					}
				}
				getMore(remIPClient, fField, fType, l, dnList, setAdminMode)
			}
			t.ExecuteTemplate(w, "index", dnList)
		}
	} else {
		dnList := make(map[string]tList, xGetCkl)
		for ckl1 = 0; ckl1 < xGetCkl; ckl1++ {
			//			fmt.Printf("GET: %s / %d\n", xGetDN[ckl1], ckl1)
			search := ldap.NewSearchRequest(xGetDN[ckl1], 0, ldap.NeverDerefAliases, 0, 0, false, "(objectClass=inetOrgPerson)", ldap_Attr, nil)
			//			fmt.Printf("GET: %v\n", search)
			sr, err := l.Search(search)
			if err != nil {
				fmt.Printf(err.Error())
				//				fmt.Fprintf(w, err.Error())
				log.Printf("LDAP::Search() error: %v %v\n", search, err)
				continue
			}
			fType := "User"
			fField := make(map[string]string, len(rconf.WLB_LDAP_ATTR))
			fField["DN"] = xGetDN[ckl1]
			if len(sr.Entries) > 0 {
				for _, entry := range sr.Entries {
					for _, attr := range entry.Attributes {
						for ckl2 := 0; ckl2 < len(rconf.WLB_LDAP_ATTR); ckl2++ {
							if attr.Name == rconf.WLB_LDAP_ATTR[ckl2][0] {
								fField[rconf.WLB_LDAP_ATTR[ckl2][1]] = fmt.Sprintf("%s", strings.Join(attr.Values, ","))
								//								fmt.Printf("Name: %s==%s --> %s = %s\n", attr.Name, rconf.WLB_LDAP_ATTR[ckl1][0], rconf.WLB_LDAP_ATTR[ckl1][1], fField[rconf.WLB_LDAP_ATTR[ckl1][1]])
							}
						}

					}
				}
			}
			getMore(remIPClient, fField, fType, l, dnList, setAdminMode)
		}
		t.ExecuteTemplate(w, "index", dnList)
	}

	t, err = template.ParseFiles("templates/footer.html")
	if err != nil {
		fmt.Fprintf(w, err.Error())
		log.Println(err.Error())
		return
	}

	t.ExecuteTemplate(w, "footer", template.FuncMap{"WebBookVersion": pVersion, "xMailBT": rconf.WLB_MailBT, "LineColor": "#EEEEEE"})
}
Example #6
0
func davDNHandler(w http.ResponseWriter, r *http.Request) {
	var (
		uid       string
		uAction   string
		uFullname string
		queryx    string
		err       error
		l         *ldap.Conn
		xFRColor  = string("#FFFFFF")
		xBGColor  = string("#FFFFFF")
	)

	_, userperm := CheckUserSession(r, w)

	switch userperm {
	case roleAdmin:
		//xFRColor = "#FF0000"
		//xBGColor = "#FFFFFF"
	default:
		return
	}

	SABModules.Log_ON(&rconf)
	defer SABModules.Log_OFF()

	remIPClient := getIPAddress(r)

	uid = r.FormValue("uid")
	uAction = r.FormValue("action")

	dbpg, err := sql.Open("postgres", rconf.PG_DSN)
	if err != nil {
		log.Fatalf("PG_INIT::Open() error: %v\n", err)
	}

	defer dbpg.Close()

	queryx = fmt.Sprintf("select fullname from ldapx_persons where uid='%s';", uid)
	rows, err := dbpg.Query(queryx)
	if err != nil {
		log.Printf("%s\n", queryx)
		log.Printf("PG::Query() Get User Name for UID: %v\n", err)
		return
	}
	rows.Next()
	rows.Scan(&uFullname)

	if uAction == "SaveDN" && len(uFullname) > 0 {

		queryx = fmt.Sprintf("select id from aaa_logins where uid='%s';", uid)
		rows, err := dbpg.Query(queryx)
		if err != nil {
			log.Printf("%s\n", queryx)
			log.Printf("PG::Query() Get User ID for UID: %v\n", err)
			return
		}

		xId := 0
		rows.Next()
		rows.Scan(&xId)

		queryx = fmt.Sprintf("delete from aaa_dns where userid=%d;", xId)
		_, err = dbpg.Query(queryx)
		if err != nil {
			log.Printf("%s\n", queryx)
			log.Printf("PG::Query() Delete DNs for UID: %v\n", err)
			return
		}
		time.Sleep(time.Second)
		r.ParseForm()
		for parName := range r.Form {
			if strings.Contains(parName, "SaveDN") {

				queryx = fmt.Sprintf("insert into aaa_dns (userid,dn) select %d, dn from ldap_entries where uid='%s';", xId, r.FormValue(parName))
				//fmt.Printf("%s\n", queryx)
				_, err = dbpg.Query(queryx)
				if err != nil {
					log.Printf("%s\n", queryx)
					log.Printf("PG::Query() Insert DNs for UID: %v\n", err)
					return
				}
				//fmt.Fprintf(w, "%v\n", r.FormValue(parName))
			}
		}

		queryx = fmt.Sprintf("insert into aaa_dav_ntu (userid,updtime) select %d,%v where not exists (select userid from aaa_dav_ntu where userid=%d); update aaa_dav_ntu set updtime=%v where userid=%d;", xId, time.Now().Unix(), xId, time.Now().Unix(), xId)
		//fmt.Printf("%s\n", queryx)
		_, err = dbpg.Query(queryx)
		if err != nil {
			log.Printf("%s\n", queryx)
			log.Printf("PG::Query() Update NTU table: %v\n", err)
			return
		}

		log.Printf("%s --> Set DavDN List for %s", remIPClient, uFullname)

		time.Sleep(time.Second)
		fmt.Fprintf(w, "<script type=\"text/javascript\">window.close();</script>")

	} else {

		log.Printf("%s <-- Get DavDN List for %s", remIPClient, uFullname)

		if initLDAPConnector() == "error" {
			return
		}

		l, err = ldap.Dial("tcp", rconf.LDAP_URL[ldap_count][0])
		if err != nil {
			fmt.Fprintf(w, err.Error())
			log.Printf("LDAP::Initialize() error: %v\n", err)
			return
		}

		//		l.Debug = true
		defer l.Close()

		log.Printf("%s =!= Connected to server %d of %d: %s", remIPClient, ldap_count+1, len(rconf.LDAP_URL), rconf.LDAP_URL[ldap_count][0])

		err = l.Bind(rconf.LDAP_URL[ldap_count][1], rconf.LDAP_URL[ldap_count][2])
		if err != nil {
			fmt.Fprintf(w, err.Error())
			log.Printf("LDAP::Bind() error: %v\n", err)
			return
		}

		t, err := template.ParseFiles("templates/header.html")
		if err != nil {
			fmt.Fprintf(w, err.Error())
			log.Println(err.Error())
			return
		}
		t.ExecuteTemplate(w, "header", template.FuncMap{"Pagetitle": rconf.WLB_HTML_Title, "FRColor": xFRColor, "BGColor": xBGColor, "TREEOn": "Yes"})

		t, err = template.ParseFiles("templates/tree-00.html")
		if err != nil {
			fmt.Fprintf(w, err.Error())
			log.Println(err.Error())
			return
		}
		t.ExecuteTemplate(w, "tree-00", template.FuncMap{"UID": uid})

		queryx = fmt.Sprintf("select distinct uid from ldap_entries where lower(dn)=lower('%s') limit 1;", rconf.LDAP_URL[ldap_count][3])
		rows, err := dbpg.Query(queryx)
		if err != nil {
			log.Printf("%s\n", queryx)
			log.Printf("PG::Query() Get UID for DN: %v\n", err)
			return
		}
		rows.Next()
		uidDN := ""
		rows.Scan(&uidDN)

		queryx = fmt.Sprintf("select z.uid from aaa_dns as x, aaa_logins as y, ldap_entries as z where x.userid=y.id and x.dn=z.dn and y.uid='%s';", uid)
		//fmt.Printf("%s\n", queryx)
		rows, err = dbpg.Query(queryx)
		if err != nil {
			log.Printf("%s\n", queryx)
			log.Printf("PG::Query() Get UID for DN: %v\n", err)
			return
		}

		dnList := make([]string, 0)

		x := ""
		for rows.Next() {
			rows.Scan(&x)
			dnList = append(dnList, x)
			//fmt.Printf("%s\n", x)
		}

		//fmt.Printf("%v\n", dnList)

		getLDAPdnList(l, uidDN, 0, rconf.WLB_DavDNTreeDepLev, w, r, dnList)

		t, err = template.ParseFiles("templates/tree-10.html")
		if err != nil {
			fmt.Fprintf(w, err.Error())
			log.Println(err.Error())
			return
		}
		t.ExecuteTemplate(w, "tree-10", nil)

	}
}