示例#1
0
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)
	}
	go_lib.LogInfof("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
		}
	}
	go_lib.LogInfof("Delete session cookie (value=%s)...\n", self.sessionId)
	hmSessionCookie.Delete(SESSION_COOKIE_KEY, self.w)
	go_lib.LogInfof("The session (key=%s) is destroyed. \n", self.key)
	return true, nil
}
示例#2
0
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()
		go_lib.LogInfof("Current Code: '%s'\n", currentAuthCode)
	} else {
		initialAuthCode := generateInitialAuthCode()
		go_lib.LogInfof("Initial Auth Code: '%s'\n", initialAuthCode)
		err = pushAuthCode(initialAuthCode, conn)
		if err != nil {
			return "", err
		}
		currentAuthCode = initialAuthCode
	}
	return currentAuthCode, nil
}
示例#3
0
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]
	go_lib.LogInfoln(request.GetRequestInfo(r))
	auth_code := r.FormValue(request.AUTH_CODE)
	go_lib.LogInfof("Getting CV by user '%s' with input '%s'...\n", loginName, auth_code)
	pass, err := request.VerifyAuthCode(auth_code)
	if err != nil {
		go_lib.LogErrorf("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 {
		go_lib.LogWarnf("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 {
		go_lib.LogErrorf("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)
	go_lib.LogInfof("The CV had taken by user '%s' with input '%s'.\n", loginName, auth_code)
}
示例#4
0
文件: admin.go 项目: hyl87/hypermind
func GetAuthCodeForAdmin(w http.ResponseWriter, r *http.Request) {
	hj, ok := w.(http.Hijacker)
	if !ok {
		errorMsg := "The Web Server does not support Hijacking! "
		http.Error(w, errorMsg, http.StatusInternalServerError)
		go_lib.LogErrorf(errorMsg)
		return
	}
	conn, bufrw, err := hj.Hijack()
	if err != nil {
		errorMsg := "Internal error!"
		http.Error(w, errorMsg, http.StatusInternalServerError)
		go_lib.LogErrorf(errorMsg+" Hijacking Error: %s\n", err)
		return
	}
	defer conn.Close()
	r.ParseForm()
	reqType := r.FormValue("type")
	go_lib.LogInfoln(request.GetRequestInfo(r))
	attrMap := request.GenerateBasicAttrMap(w, r)
	loginName := attrMap[request.LOGIN_NAME_KEY]
	groupName := attrMap[request.GROUP_NAME_KEY]
	parameterOutline := fmt.Sprintf("[loginName=%s, groupName=%s, reqType=%s]", loginName, groupName, reqType)
	if groupName != rights.ADMIN_USER_GROUP_NAME {
		errorMsg := "Authentication failed!"
		http.Error(w, errorMsg, http.StatusForbidden)
		go_lib.LogErrorf(errorMsg+" [auth code push handler] %s \n", parameterOutline)
		return
	}
	if reqType != "lp" {
		currentAuthCode, err := request.GetCurrentAuthCode()
		if err != nil {
			go_lib.LogErrorf("GetCurrentAuthCodeError: %s\n", err)
		}
		go_lib.LogInfof("Push current auth code '%s' %s \n", currentAuthCode, parameterOutline)
		done := pushResponse(bufrw, currentAuthCode)
		if !done {
			go_lib.LogErrorf("Pushing current auth code '%s' is failing! %s \n", currentAuthCode, parameterOutline)
		}
	} else {
		nacChan := make(chan string)
		triggerFunc := func(newAuthCode string) {
			nacChan <- newAuthCode
		}
		triggerId := fmt.Sprintf("long-polling|%s|%s|%d", loginName, groupName, time.Now().UnixNano())
		request.AddNewAuthCodeTrigger(triggerId, triggerFunc)
		defer request.DelNewAuthCodeTrigger(triggerId)
		newAuthCode := <-nacChan // wait for new auth code generating
		go_lib.LogInfof("Push new auth code '%s' %s \n", newAuthCode, parameterOutline)
		done := pushResponse(bufrw, newAuthCode)
		if !done {
			go_lib.LogErrorf("Pushing new auth code '%s' is failing! %s \n", newAuthCode, parameterOutline)
		}
	}
	defer go_lib.LogInfof("The auth code push handler will be close. %s \n", parameterOutline)
}
示例#5
0
func init() {
	newAuthCodeTriggerMap = make(map[string]NewAuthCodeTrigger)
	firstNewAuthCodeTrigger := func(newAuthCode string) {
		go_lib.LogInfof("There has a new auth code '%s'.", newAuthCode)
	}
	AddNewAuthCodeTrigger("monitoring", firstNewAuthCodeTrigger)
}
示例#6
0
func DeleteTempFile(delay time.Duration, filePath string) (err error) {
	time.Sleep(delay)
	err = os.Remove(filePath)
	if err != nil {
		go_lib.LogErrorf("Occur error when delete file '%s': %s\n", filePath, err)
	} else {
		go_lib.LogInfof("The file '%s' is deleted.\n", filePath, err)
	}
	return
}
示例#7
0
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
	}
	go_lib.LogInfof("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
}
示例#8
0
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 {
		go_lib.LogErrorf("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 {
				go_lib.LogErrorf("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 {
		go_lib.LogInfof("The page access info has been cleared. %s\n", parameterInfo)
	} else {
		go_lib.LogWarnf("The page access info failed to clear. %s\n", parameterInfo)
	}
	return result, nil
}
示例#9
0
文件: server.go 项目: hyl87/hypermind
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)
	go_lib.LogInfof("Starting hypermind http server (port=%d)...\n", serverPort)
	err := http.ListenAndServe(":"+fmt.Sprintf("%d", serverPort), nil)
	if err != nil {
		go_lib.LogFatalln("ListenAndServeError: ", err)
	} else {
		go_lib.LogInfoln("Hypermind http server is started.")
	}
}
示例#10
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)
}
示例#11
0
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)
	go_lib.LogInfof("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
	}
	go_lib.LogInfof("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 {
		go_lib.LogInfof("Session cookie setting (value=%s, grantors=%s, maxAge=%d) is successful.\n", self.sessionId, grantors, cookieMaxAge)
	} else {
		go_lib.LogWarnf("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)
			go_lib.LogWarnln(warningMsg)
		}
	}
	_, err = dao.SetHash(SESSION_MAP_KEY, grantors, self.key)
	if err != nil {
		return err
	}
	return nil
}
示例#12
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)
	}
}