示例#1
0
func Upload(w http.ResponseWriter, r *http.Request) {
	go_lib.LogInfoln(request.GetRequestInfo(r))
	if r.Method == "GET" {
		token := r.Form.Get("token")
		t, _ := template.ParseFiles(request.GeneratePagePath("upload"))
		err := t.Execute(w, token)
		if err != nil {
			go_lib.LogErrorln("PageWriteErr:", err)
		}
	} else {
		r.ParseMultipartForm(32 << 20)
		file, handler, err := r.FormFile("uploadfile")
		if err != nil {
			go_lib.LogErrorln("UploadFileParsError:", err)
			return
		}
		defer file.Close()
		fmt.Fprintf(w, "%v", handler.Header)
		var buffer bytes.Buffer
		buffer.WriteString(os.TempDir())
		buffer.WriteString("/")
		buffer.WriteString(handler.Filename)
		tempFilePath := buffer.String()
		f, err := os.OpenFile(tempFilePath, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			go_lib.LogErrorln(err)
			return
		}
		defer f.Close()
		go_lib.LogInfoln("Receive a file & save to %s ...\n", tempFilePath)
		io.Copy(f, file)
		go request.DeleteTempFile(time.Duration(time.Minute*5), tempFilePath)
	}
}
示例#2
0
func RequestDispatcher(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	go_lib.LogInfoln(request.GetRequestInfo(r))
	attrMap := request.GenerateBasicAttrMap(w, r)
	currentPage := r.FormValue("page")
	if len(currentPage) == 0 {
		currentPage = base.HOME_PAGE
	}
	pageRightsTag := attrMap[currentPage]
	if pageRightsTag != "true" {
		currentPage = base.HOME_PAGE
	}
	t := template.New("welcome page")
	t.Funcs(template.FuncMap{
		"equal":   request.SimpleEqual,
		"match":   request.MatchString,
		"allTrue": request.AllTrue,
	})
	t, err := t.ParseFiles(request.GeneratePagePath(currentPage),
		request.GeneratePagePath("common"),
		request.GeneratePagePath("navbar"))
	if err != nil {
		go_lib.LogErrorln("ParseFilesErr:", err)
	}
	attrMap["currentPage"] = currentPage
	err = t.ExecuteTemplate(w, "page", attrMap)
	if err != nil {
		go_lib.LogErrorln("ExecuteTemplateErr:", err)
	}
	recordPageAccessInfo(currentPage, attrMap[request.LOGIN_NAME_KEY], uint64(1))
}
示例#3
0
func init() {
	hmConfig = go_lib.Config{Path: CONFIG_FILE_NAME}
	err := hmConfig.ReadConfig(false)
	if err != nil {
		go_lib.LogErrorln("ConfigLoadError: ", err)
	}
}
示例#4
0
func Register(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	go_lib.LogInfoln(request.GetRequestInfo(r))
	if r.Method == "GET" {
		attrMap := request.GenerateBasicAttrMap(w, r)
		encodedHint := r.FormValue("hint")
		if len(encodedHint) > 0 {
			hint := request.UrlDecoding(encodedHint)
			attrMap["hint"] = hint
		}
		t, _ := template.ParseFiles(request.GeneratePagePath("register"))
		err := t.Execute(w, attrMap)
		if err != nil {
			go_lib.LogErrorln("PageWriteErr:", err)
		}
	} else {
		fieldMap, invalidFields := request.VerifyRegisterForm(r)
		go_lib.LogInfoln("The field map:", fieldMap)
		if len(invalidFields) > 0 {
			hint := fmt.Sprintln("There are some invalid fields of '':", invalidFields, ".")
			go_lib.LogInfoln(hint)
			encodedHint := request.UrlEncoding(hint)
			redirectUrl := "/register?hint=" + encodedHint
			http.Redirect(w, r, redirectUrl, http.StatusFound)
		} else {
			http.Redirect(w, r, "/", http.StatusFound)
		}
	}
}
示例#5
0
func GetSessionMap(w http.ResponseWriter, r *http.Request) map[string]string {
	var sessionMap map[string]string
	hmSession, err := GetSession(w, r)
	if err != nil {
		go_lib.LogErrorln("GetSessionError: %s\n", err)
		return sessionMap
	}
	if hmSession != nil {
		sessionMap, err = hmSession.GetAll()
		if err != nil {
			go_lib.LogErrorln("SessionGetAllError: %s\n", err)
			return sessionMap
		}
	}
	return sessionMap
}
示例#6
0
func GenerateBasicAttrMap(w http.ResponseWriter, r *http.Request) map[string]string {
	attrMap := make(map[string]string)
	host, port := splitHostPort(r.Host)
	attrMap["serverAddr"] = host
	attrMap["serverPort"] = port
	for pageKey, page := range pageParameterMap {
		attrMap[pageKey] = page
	}
	hmSession, err := GetSession(w, r)
	if err != nil {
		go_lib.LogErrorln("GetSessionError: %s\n", err)
	} else {
		var pageRights map[string]string
		var loginName string
		var groupName string
		if hmSession != nil {
			pageRights = getPageRights(hmSession)
			loginName = getLoginName(hmSession)
			groupName = getGroupName(hmSession)
		} else {
			pageRights = rights.GetGuestPageRights()
			loginName = ""
			groupName = ""
		}
		for p, pr := range pageRights {
			attrMap[p] = pr
		}
		attrMap[LOGIN_NAME_KEY] = loginName
		attrMap[GROUP_NAME_KEY] = groupName
	}
	return attrMap
}
示例#7
0
func GetRequestInfo(r *http.Request) string {
	requestInfo := RequestInfo{Form: r.Form, Method: r.Method, Path: r.URL.Path, Scheme: r.URL.Scheme}
	b, err := json.Marshal(requestInfo)
	if err != nil {
		go_lib.LogErrorln("JsonMarshalError:", err)
	}
	return string(b)
}
示例#8
0
func getLoginName(hmSession *session.MySession) string {
	if hmSession == nil {
		return ""
	}
	grantors, err := hmSession.Get(session.SESSION_GRANTORS_KEY)
	if err != nil {
		go_lib.LogErrorln("SessionGetError (field=%s): %s\n", session.SESSION_GRANTORS_KEY, err)
		return ""
	}
	return grantors
}
示例#9
0
func getPageRights(hmSession *session.MySession) map[string]string {
	var pageRights map[string]string
	if hmSession == nil {
		return pageRights
	}
	groupName, err := hmSession.Get(session.SESSION_GROUP_KEY)
	if err != nil {
		go_lib.LogErrorln("SessionGetError (field=%s): %s\n", session.SESSION_GROUP_KEY, err)
		return pageRights
	}
	userGroup, err := rights.GetUserGroup(groupName)
	if err != nil {
		go_lib.LogErrorln("GetUserGroupError (groupName=%s): %s\n", groupName, err)
		return pageRights
	}
	if userGroup != nil {
		pageRights = userGroup.Rights.PageRights
	}
	return pageRights
}
示例#10
0
func getGroupName(hmSession *session.MySession) string {
	if hmSession == nil {
		return ""
	}
	groupName, err := hmSession.Get(session.SESSION_GROUP_KEY)
	if err != nil {
		go_lib.LogErrorln("SessionGetError (field=%s): %s\n", session.SESSION_GROUP_KEY, err)
		return ""
	}
	return groupName
}
示例#11
0
func Logout(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	go_lib.LogInfoln(request.GetRequestInfo(r))
	hmSession, err := session.GetMatchedSession(w, r)
	if err != nil {
		go_lib.LogErrorln("GetSessionErr:", err)
	}
	if hmSession != nil {
		loginName, err := hmSession.Get(session.SESSION_GRANTORS_KEY)
		if err != nil {
			go_lib.LogErrorln("GetLoginNameErr:", err)
		}
		done, err := hmSession.Destroy()
		if err != nil {
			go_lib.LogErrorln("DestroySessionErr:", err)
		} else {
			go_lib.LogInfof("Logout: User '%s' logout. (result=%v)\n", loginName, done)
		}
	} else {
		go_lib.LogInfoln("Logout: Current visitor has yet login.\n")
	}
	http.Redirect(w, r, "/", http.StatusFound)
}
示例#12
0
func splitHostPort(requestHost string) (host string, port string) {
	if splitIndex := strings.Index(requestHost, ":"); splitIndex > 0 {
		host = requestHost[0:splitIndex]
		port = requestHost[splitIndex+1 : len(requestHost)]
	} else {
		host = requestHost
		config := base.GetHmConfig()
		err := config.ReadConfig(false)
		if err != nil {
			go_lib.LogErrorln("ConfigLoadError: ", err)
			port = "80"
		} else {
			port = fmt.Sprintf("%v", config.Dict["server_port"])
		}
	}
	return
}
示例#13
0
文件: redis.go 项目: hyl87/hypermind
func init() {
	config := GetHmConfig()
	err := config.ReadConfig(false)
	if err != nil {
		go_lib.LogErrorln("ConfigLoadError: ", err)
	}
	redisServerIp = config.Dict["redis_server_ip"]
	if len(redisServerIp) == 0 {
		redisServerIp = DEFAULT_REDIS_SERVER_IP
	}
	redisServerPort = config.Dict["redis_server_port"]
	if len(redisServerPort) == 0 {
		redisServerPort = DEFAULT_REDIS_SERVER_PORT
	}
	redisServerPassword = config.Dict["redis_server_password"]
	if len(redisServerPassword) == 0 {
		redisServerPassword = DEFAULT_REDIS_SERVER_PASSWORD
	}
	redisServerAddr := "127.0.0.1" + ":" + redisServerPort
	RedisPool = &redis.Pool{
		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", redisServerAddr)
			if err != nil {
				return nil, err
			}
			if len(redisServerPassword) > 0 {
				if _, err := c.Do("AUTH", redisServerPassword); err != nil {
					c.Close()
					return nil, err
				}
			}
			return c, err
		},
	}
}
示例#14
0
func Login(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	go_lib.LogInfoln(request.GetRequestInfo(r))
	attrMap := request.GenerateBasicAttrMap(w, r)
	loginName := attrMap[request.LOGIN_NAME_KEY]
	if r.Method == "GET" {
		token := request.GenerateToken(r, loginName)
		go_lib.LogInfof("Token: %v\n", token)
		request.SaveToken(token)
		attrMap := request.GenerateBasicAttrMap(w, r)
		attrMap[request.TOKEN_KEY] = token.Key
		hint := r.FormValue(request.HINT_KEY)
		if len(hint) > 0 {
			attrMap[request.HINT_KEY] = hint
		}
		t, err := template.ParseFiles(request.GeneratePagePath("login"), request.GeneratePagePath("common"))
		if err != nil {
			go_lib.LogErrorln("TemplateParseErr:", err)
		}
		err = t.ExecuteTemplate(w, "page", attrMap)
		if err != nil {
			go_lib.LogErrorln("PageWriteErr:", err)
		}
	} else {
		r.ParseForm()
		tokenKey := r.Form.Get(request.TOKEN_KEY)
		go_lib.LogInfoln("Token Key:", tokenKey)
		validToken := request.CheckToken(tokenKey)
		if !validToken {
			go_lib.LogWarnf("Invalid token key '%s' ! Ignore the login request.", tokenKey)
			r.Method = "GET"
			http.Redirect(w, r, r.URL.Path, http.StatusFound)
			return
		} else {
			request.RemoveToken(tokenKey)
		}
		loginName = template.HTMLEscapeString(r.Form.Get(request.LOGIN_NAME_KEY))
		go_lib.LogInfoln("login - loginName:", loginName)
		password := template.HTMLEscapeString(r.Form.Get(request.PASSWORD_KEY))
		go_lib.LogInfoln("login - password:"******"remember-me")
		go_lib.LogInfoln("login - remember-me:", rememberMe)
		validLogin, err := rights.VerifyUser(loginName, password)
		go_lib.LogInfoln("Verify user:"******"/"
		if err != nil {
			go_lib.LogErrorf("VerifyUserError (loginName=%s): %s\n", loginName, err)
			redirectPath = r.URL.Path
		} else {
			if validLogin {
				longTerm := len(rememberMe) == 0 || rememberMe != "y"
				_, err = session.NewSession(loginName, longTerm, w, r)
				if err != nil {
					go_lib.LogErrorf("SetSessionError (loginName=%s): %s\n", loginName, err)
				}
			} else {
				hint := "Wrong login name or password."
				redirectPath = request.AppendParameter(r.URL.Path, map[string]string{request.HINT_KEY: hint})
			}
		}
		go_lib.LogInfof("RPATH: %s\n", redirectPath)
		http.Redirect(w, r, redirectPath, http.StatusFound)
	}
}