func Upload(w http.ResponseWriter, r *http.Request) { base.Logger().Infoln(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 { base.Logger().Errorln("PageWriteErr:", err) } } else { r.ParseMultipartForm(32 << 20) file, handler, err := r.FormFile("uploadfile") if err != nil { base.Logger().Errorln("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 { base.Logger().Errorln(err) return } defer f.Close() base.Logger().Infoln("Receive a file & save to %s ...\n", tempFilePath) io.Copy(f, file) go request.DeleteTempFile(time.Duration(time.Minute*5), tempFilePath) } }
func RequestDispatcher(w http.ResponseWriter, r *http.Request) { r.ParseForm() base.Logger().Infoln(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 { base.Logger().Errorln("ParseFilesErr:", err) } attrMap["currentPage"] = currentPage err = t.ExecuteTemplate(w, "page", attrMap) if err != nil { base.Logger().Errorln("ExecuteTemplateErr:", err) } recordPageAccessInfo(currentPage, attrMap[request.LOGIN_NAME_KEY], uint64(1)) }
func GetCurrentAuthCode() (string, error) { conn := dao.RedisPool.Get() defer conn.Close() values, err := redis.Values(conn.Do("LRANGE", dao.AUTH_CODE_KEY, 0, 0)) if err != nil { return "", err } var currentAuthCode string if len(values) > 0 { var buffer bytes.Buffer value := values[0] valueBytes := value.([]byte) for _, v := range valueBytes { buffer.WriteByte(v) } currentAuthCode = buffer.String() base.Logger().Infof("Current Code: '%s'\n", currentAuthCode) } else { initialAuthCode := generateInitialAuthCode() base.Logger().Infof("Initial Auth Code: '%s'\n", initialAuthCode) err = pushAuthCode(initialAuthCode, conn) if err != nil { return "", err } currentAuthCode = initialAuthCode } return currentAuthCode, nil }
func (self *MySession) Destroy() (bool, error) { if len(self.key) == 0 || len(self.sessionId) == 0 { errorMsg := fmt.Sprintln("Uninitialized yet!") return false, errors.New(errorMsg) } base.Logger().Infof("Destroy session (key=%s)... \n", self.key) grantors, err := dao.GetHash(self.key, SESSION_GRANTORS_KEY) if err != nil { return false, err } _, err = dao.DelKey(self.key) if err != nil { return false, err } if len(grantors) > 0 { _, err = dao.DelHashField(SESSION_MAP_KEY, grantors) if err != nil { return false, err } } base.Logger().Infof("Delete session cookie (value=%s)...\n", self.sessionId) hmSessionCookie.Delete(SESSION_COOKIE_KEY, self.w) base.Logger().Infof("The session (key=%s) is destroyed. \n", self.key) return true, nil }
func Register(w http.ResponseWriter, r *http.Request) { r.ParseForm() base.Logger().Infoln(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 { base.Logger().Errorln("PageWriteErr:", err) } } else { fieldMap, invalidFields := request.VerifyRegisterForm(r) base.Logger().Infoln("The field map:", fieldMap) if len(invalidFields) > 0 { hint := fmt.Sprintln("There are some invalid fields of '':", invalidFields, ".") base.Logger().Infoln(hint) encodedHint := request.UrlEncoding(hint) redirectUrl := "/register?hint=" + encodedHint http.Redirect(w, r, redirectUrl, http.StatusFound) } else { http.Redirect(w, r, "/", http.StatusFound) } } }
func DeleteTempFile(delay time.Duration, filePath string) (err error) { time.Sleep(delay) err = os.Remove(filePath) if err != nil { base.Logger().Errorf("Occur error when delete file '%s': %s\n", filePath, err) } else { base.Logger().Infof("The file '%s' is deleted.\n", filePath, err) } return }
func init() { newAuthCodeTriggerMap = make(map[string]NewAuthCodeTrigger) firstNewAuthCodeTrigger := func(newAuthCode string) { base.Logger().Infof("There has a new auth code '%s'.", newAuthCode) } AddNewAuthCodeTrigger("monitoring", firstNewAuthCodeTrigger) }
func GetSessionMap(w http.ResponseWriter, r *http.Request) map[string]string { var sessionMap map[string]string hmSession, err := GetSession(w, r) if err != nil { base.Logger().Errorln("GetSessionError: %s\n", err) return sessionMap } if hmSession != nil { sessionMap, err = hmSession.GetAll() if err != nil { base.Logger().Errorln("SessionGetAllError: %s\n", err) return sessionMap } } return sessionMap }
func VerifyAuthCode(authCode string) (bool, error) { if len(authCode) == 0 { return false, nil } currentAuthCode, err := GetCurrentAuthCode() var pass bool if err == nil { pass = (currentAuthCode == strings.TrimSpace(authCode)) } if pass { go func() { var newAuthCode string for { newAuthCode = generateAuthCode() if newAuthCode != currentAuthCode { break } } if len(newAuthCode) > 0 { conn := dao.RedisPool.Get() defer conn.Close() err = pushAuthCode(newAuthCode, conn) if err != nil { base.Logger().Errorf("New auth code pushing error: %s\n", err) } } }() } return pass, err }
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 { base.Logger().Errorln("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 }
func GetMatchedSession(w http.ResponseWriter, r *http.Request) (*MySession, error) { sessionId := hmSessionCookie.GetOne(SESSION_COOKIE_KEY, r) if len(sessionId) == 0 { warningMsg := fmt.Sprintf("Not found matched session! No session cookie!") base.Logger().Warnln(warningMsg) return nil, nil } sessionkey := generateSessionKey(sessionId) exists, err := dao.Exists(sessionkey) if err != nil { return nil, err } if !exists { warningMsg := fmt.Sprintf("Not found matched session! No session in storage! (sessionId=%s, sessionKey=%s)", sessionId, sessionkey) base.Logger().Warnln(warningMsg) return nil, nil } grantors, err := dao.GetHash(sessionkey, SESSION_GRANTORS_KEY) if err != nil { return nil, err } if len(grantors) == 0 { warningMsg := fmt.Sprintf("Not found grantor from session (sessionKey=%s, attribute=%s)!\n", sessionkey, SESSION_GRANTORS_KEY) base.Logger().Warnln(warningMsg) return nil, nil } groupName, err := dao.GetHash(sessionkey, SESSION_GROUP_KEY) if err != nil { return nil, err } if len(groupName) == 0 { warningMsg := fmt.Sprintf("Not found group name from session (sessionKey=%s, attribute=%s)!\n", sessionkey, SESSION_GROUP_KEY) base.Logger().Warnln(warningMsg) return nil, err } servivalSecondsLiterals, err := dao.GetHash(sessionkey, SESSION_SURVIVAL_SECONDS_KEY) if err != nil { return nil, err } if len(servivalSecondsLiterals) == 0 { warningMsg := fmt.Sprintf("Not found session servival seconds. Use default value '0'. (sessionKey=%s, attribute=%s)!\n", sessionkey, SESSION_SURVIVAL_SECONDS_KEY) base.Logger().Warnln(warningMsg) return nil, err } hmSession := &MySession{key: sessionkey, sessionId: sessionId, w: w, r: r} return hmSession, nil }
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 { base.Logger().Errorln("JsonMarshalError:", err) } return string(b) }
func getGroupName(hmSession *session.MySession) string { if hmSession == nil { return "" } groupName, err := hmSession.Get(session.SESSION_GROUP_KEY) if err != nil { base.Logger().Errorln("SessionGetError (field=%s): %s\n", session.SESSION_GROUP_KEY, err) return "" } return groupName }
func recordPageAccessInfo(pageName string, visitor string, number uint64) bool { var result bool done, err := statistics.AddPageAccessRecord(pageName, visitor, number) if err != nil { base.Logger().Errorf("Adding page access record error: %s (pageName=%s, visitor=%s, number=%d)\n", err, pageName, visitor, number) result = false } else { result = done } return result }
func pushResponse(bufrw *bufio.ReadWriter, authCode string) bool { _, err := bufrw.Write([]byte(authCode)) if err == nil { err = bufrw.Flush() } if err != nil { base.Logger().Errorf("PushAuthCodeError: %s\n", err) return false } return true }
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 { base.Logger().Errorln("SessionGetError (field=%s): %s\n", session.SESSION_GROUP_KEY, err) return pageRights } userGroup, err := rights.GetUserGroup(groupName) if err != nil { base.Logger().Errorln("GetUserGroupError (groupName=%s): %s\n", groupName, err) return pageRights } if userGroup != nil { pageRights = userGroup.Rights.PageRights } return pageRights }
func getLoginName(hmSession *session.MySession) string { if hmSession == nil { return "" } grantors, err := hmSession.Get(session.SESSION_GRANTORS_KEY) if err != nil { base.Logger().Errorln("SessionGetError (field=%s): %s\n", session.SESSION_GRANTORS_KEY, err) return "" } return grantors }
func ClearPageAccessRecord(pageName string, visitor string) (bool, error) { if len(pageName) == 0 { return false, errors.New("The parameter named pageName is EMPTY!") } sign := getSignForPage(pageName) sign.Set() defer sign.Unset() parameterInfo := fmt.Sprintf("(pageName=%s, visitor=%s)", pageName, visitor) var result bool conn := dao.RedisPool.Get() defer conn.Close() value, err := dao.GetHash(dao.PAGE_ACCESS_RECORDS_KEY, pageName) if err != nil { return false, err } visitorAccessRecords, err := parseVisitorAccessRecords(value) if err != nil { base.Logger().Errorf("Parsing visitor access records error: %s %s\n", err, parameterInfo) } if visitorAccessRecords != nil { _, ok := visitorAccessRecords[visitor] if ok { delete(visitorAccessRecords, visitor) literals, err := formatVisitorAccessRecords(visitorAccessRecords) if err != nil { base.Logger().Errorf("Formating visitor access records error: %s %s\n", err, parameterInfo) } else { result, err = dao.SetHash(dao.PAGE_ACCESS_RECORDS_KEY, pageName, literals) if err != nil { return false, err } } } } if result { base.Logger().Infof("The page access info has been cleared. %s\n", parameterInfo) } else { base.Logger().Warnf("The page access info failed to clear. %s\n", parameterInfo) } return result, nil }
func GetCv(w http.ResponseWriter, r *http.Request) { r.ParseForm() w.WriteHeader(200) w.Header().Set("Content-Type", "text/html; charset=utf-8") attrMap := request.GenerateBasicAttrMap(w, r) loginName := attrMap[request.LOGIN_NAME_KEY] base.Logger().Infoln(request.GetRequestInfo(r)) auth_code := r.FormValue(request.AUTH_CODE) base.Logger().Infof("Getting CV by user '%s' with input '%s'...\n", loginName, auth_code) pass, err := request.VerifyAuthCode(auth_code) if err != nil { base.Logger().Errorf("Occur error when verify auth code: %s\n", err) // w.WriteHeader(500) fmt.Fprintln(w, "Error: Something wrong when verify auth code!") return } if !pass { base.Logger().Warnf("Unauthorized CV getting by user '%s' with input '%s'.\n", loginName, auth_code) // w.WriteHeader(401) fmt.Fprintln(w, "FAIL: Wrong authorization code.") return } cvContent, err := base.GetCvContent() if err != nil { base.Logger().Errorf("Occur error when get cv content: %s.\n", err) // w.WriteHeader(500) fmt.Fprintln(w, "Error: Something wrong when get CV content!") return } fmt.Fprintln(w, cvContent) base.Logger().Infof("The CV had taken by user '%s' with input '%s'.\n", loginName, auth_code) }
func main() { flag.Parse() fileServer := http.FileServer(http.Dir("web")) http.Handle("/css/", fileServer) http.Handle("/js/", fileServer) http.Handle("/img/", fileServer) http.HandleFunc("/", controller.RequestDispatcher) http.HandleFunc("/register", controller.Register) http.HandleFunc("/login", controller.Login) http.HandleFunc("/logout", controller.Logout) http.HandleFunc("/upload", controller.Upload) http.HandleFunc("/get-cv", controller.GetCv) http.HandleFunc("/auth_code", controller.GetAuthCodeForAdmin) http.HandleFunc("/user_list", controller.GetUserListForAdmin) base.Logger().Infof("Starting hypermind http server (port=%d)...\n", serverPort) err := http.ListenAndServe(":"+fmt.Sprintf("%d", serverPort), nil) if err != nil { base.Logger().Fatalln("ListenAndServeError: ", err) } else { base.Logger().Infoln("Hypermind http server is started.") } }
func init() { for name, rights := range userGroupMap { userGroup, err := GetUserGroup(name) if err != nil { base.Logger().Errorf("Get User Group (name=%s) Error: %s\n", name, err) continue } if userGroup != nil { err = DeleteUserGroup(name) if err != nil { base.Logger().Errorf("Delete User Group (name=%s) Error: %s\n", name, err) continue } } userGroup = &UserGroup{Name: name, Rights: rights} err = AddUserGroup(userGroup) if err != nil { base.Logger().Errorf("Add User Group '%v' Error: %s\n", userGroup, err) continue } } }
func newSession(grantors string, servivalSeconds int, w http.ResponseWriter, r *http.Request) (*MySession, error) { hmSession := &MySession{} err := hmSession.Initialize(grantors, servivalSeconds, w, r) if err != nil { return nil, err } user, err := rights.GetUser(grantors) if err != nil { return nil, err } base.Logger().Infof("Set session core attribute '%s' to value '%s' for grantors '%s'. (key=%s)\n", SESSION_GROUP_KEY, user.Group, grantors, hmSession.Key()) err = hmSession.Set(SESSION_GROUP_KEY, user.Group) if err != nil { return nil, err } return hmSession, nil }
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 { base.Logger().Errorln("ConfigLoadError: ", err) port = "80" } else { port = fmt.Sprintf("%v", config.Dict["server_port"]) } } return }
func MatchString(args ...interface{}) bool { if len(args) < 2 { return false } target := args[0].(string) for _, v := range args[1:len(args)] { pattern := v.(string) pass, err := regexp.MatchString(pattern, target) if err != nil { base.Logger().Errorf("RegexpMatchError (target=%s, pattern=%s): %s\n", target, pattern, err) return false } if !pass { return false } } return true }
func Logout(w http.ResponseWriter, r *http.Request) { r.ParseForm() base.Logger().Infoln(request.GetRequestInfo(r)) hmSession, err := session.GetMatchedSession(w, r) if err != nil { base.Logger().Errorln("GetSessionErr:", err) } if hmSession != nil { loginName, err := hmSession.Get(session.SESSION_GRANTORS_KEY) if err != nil { base.Logger().Errorln("GetLoginNameErr:", err) } done, err := hmSession.Destroy() if err != nil { base.Logger().Errorln("DestroySessionErr:", err) } else { base.Logger().Infof("Logout: User '%s' logout. (result=%v)\n", loginName, done) } } else { base.Logger().Infoln("Logout: Current visitor has yet login.\n") } http.Redirect(w, r, "/", http.StatusFound) }
func (self *MySession) Initialize( grantors string, // survivalSeconds: // '<0'- Don't set/Delete cookie; // '0' - Set temporary cookie; // '>0'- Set long term cookie according to this value & Set session expires survivalSeconds int, w http.ResponseWriter, r *http.Request) error { if len(grantors) == 0 { errorMsg := fmt.Sprintln("The session grantors is EMPTY!") return errors.New(errorMsg) } if w == nil { errorMsg := fmt.Sprintln("The pointer of http response writer is NIL!") return errors.New(errorMsg) } if r == nil { errorMsg := fmt.Sprintln("The pointer of http request is NIL!") return errors.New(errorMsg) } self.w = w self.r = r self.sessionId = generateSessionId(grantors, r) self.key = generateSessionKey(self.sessionId) base.Logger().Infof("Initialize session (key=%s, grantors=%s)...\n", self.key, grantors) exists, err := dao.Exists(self.key) if err != nil { return err } if exists { _, err = dao.DelKey(self.key) if err != nil { return err } } _, err = dao.SetHash(self.key, SESSION_GRANTORS_KEY, grantors) if err != nil { return err } _, err = dao.SetHash(self.key, SESSION_SURVIVAL_SECONDS_KEY, strconv.FormatInt(int64(survivalSeconds), 10)) if err != nil { return err } cookieMaxAge := survivalSeconds if survivalSeconds <= 0 { cookieMaxAge = -1 } base.Logger().Infof("Set session cookie (value=%s, grantors=%s, maxAge=%d)...\n", self.sessionId, grantors, cookieMaxAge) result := hmSessionCookie.SetOne(self.w, SESSION_COOKIE_KEY, self.sessionId, cookieMaxAge) if result { base.Logger().Infof("Session cookie setting (value=%s, grantors=%s, maxAge=%d) is successful.\n", self.sessionId, grantors, cookieMaxAge) } else { base.Logger().Warnf("Session cookie setting (value=%s, grantors=%s, maxAge=%d) is failing!\n", self.sessionId, grantors, cookieMaxAge) } if survivalSeconds > 0 { done, err := dao.SetExpires(self.key, uint64(survivalSeconds)) if err != nil || !done { warningMsg := fmt.Sprintf("Setting session expires failed! (key=%s, survivalSeconds=%d, error=%s)\n", self.key, survivalSeconds, err) base.Logger().Warnln(warningMsg) } } _, err = dao.SetHash(SESSION_MAP_KEY, grantors, self.key) if err != nil { return err } return nil }
func Login(w http.ResponseWriter, r *http.Request) { r.ParseForm() base.Logger().Infoln(request.GetRequestInfo(r)) attrMap := request.GenerateBasicAttrMap(w, r) loginName := attrMap[request.LOGIN_NAME_KEY] if r.Method == "GET" { token := request.GenerateToken(r, loginName) base.Logger().Infof("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 { base.Logger().Errorln("TemplateParseErr:", err) } err = t.ExecuteTemplate(w, "page", attrMap) if err != nil { base.Logger().Errorln("PageWriteErr:", err) } } else { r.ParseForm() tokenKey := r.Form.Get(request.TOKEN_KEY) base.Logger().Infoln("Token Key:", tokenKey) validToken := request.CheckToken(tokenKey) if !validToken { base.Logger().Warnf("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)) base.Logger().Infoln("login - loginName:", loginName) password := template.HTMLEscapeString(r.Form.Get(request.PASSWORD_KEY)) base.Logger().Infoln("login - password:"******"remember-me") base.Logger().Infoln("login - remember-me:", rememberMe) validLogin, err := rights.VerifyUser(loginName, password) base.Logger().Infoln("Verify user:"******"/" if err != nil { base.Logger().Errorf("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 { base.Logger().Errorf("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}) } } base.Logger().Infof("RPATH: %s\n", redirectPath) http.Redirect(w, r, redirectPath, http.StatusFound) } }